[英]preg_split without the function
我想學習如何使用一組與preg_split
函數功能相同的php代碼,而不使用實際的preg_split
函數。 以這個為例
<?php
$string = '<p>i am a sentence <span id="blah"> im content inside of the span </span> im another sentence <span id="anId">i m another span content</span> im the last sentence in this p tag <span id="last">im the third span tag in this p tag<span></p>';
if ( preg_match_all("/<span[^>]*>/", $string, $temporaryArray) ) {
foreach ($temporaryArray as $values) {
$theArrayWithoutUsingPregSplit[$strpos] = $values;
}
}
?>
但是,這不起作用,因為preg_match_all
僅計算其匹配的次數,而沒有獲取實際的字符串。 但是此頁面上的人員http://php.net/manual/zh/function.preg-split.php#118326可以做到。 有人可以幫忙嗎。
另外,我想讓strpos()
函數用作每個數組元素的鍵,這樣我就可以看到$string
變量中值的位置,在本例中,我給出的變量沒有值。
嘗試從字符串變量獲取的最終輸出是
array (
[$thisVariableIsANumberWhichIsTheStrPosOfTheValue] i am a sentence
[$thisVariableIsANumberWhichIsTheStrPosOfTheValue] im content inside of the span
[$thisVariableIsANumberWhichIsTheStrPosOfTheValue] im another sentence
[$thisVariableIsANumberWhichIsTheStrPosOfTheValue] i m another span content
[$thisVariableIsANumberWhichIsTheStrPosOfTheValue] im the last sentence in this p tag
[$thisVariableIsANumberWhichIsTheStrPosOfTheValue] im the third span tag in this p tag
)
我不認為原因preg_split
在這種情況下使用的最好的事情是因為我不能有代表數組鍵strpos
值的。
非常抱歉,如果您有任何疑問,我會盡我所能使問題變得易於理解,否則人們可能會投票否決。
使用DOMDocument:
$string = '<p>i am a sentence <span id="blah"> im content inside of the span </span> im another sentence <span id="anId">i m another span content</span> im the last sentence in this p tag <span id="last">im the third span tag in this p tag<span></p>';
$dom = new DOMDocument;
$dom->loadHTML($string, LIBXML_HTML_NOIMPLIED);
$xp = new DOMXPath($dom);
foreach($xp->query('//text()') as $textNode) {
echo trim($textNode->nodeValue), PHP_EOL;
}
該方法包括在每個文本節點之后使用XPath查詢語言和簡單查詢//text()
(DOM樹中任意位置的文本節點//text()
詢問。
要在<span>
和</span>
之間獲得文本,您需要更改您的正則表達式以使其兩者匹配,並在兩者之間使用捕獲組。
$temporaryArray
是一個二維數組; 元素0
包含整個正則表達式的匹配項,元素N
包含第N個捕獲組的匹配項。 因此,您想要的字符串在$temporaryArray[1]
。 如果還需要這些位置,請使用PREG_OFFSET_CAPTURE
選項。 使用此選項,每個匹配項都是一個數組[ "string", strpos ]
。
if ( preg_match_all('#<span[^>]*>(.*?)</span>#', $string, $temporaryArray, PREG_OFFSET_CAPTURE) ) {
$theArrayWithoutUsingPregSplit = array();
foreach($temporaryArray[1] as $match) {
$theArrayWithoutUsingPregSplit[$match[1]] = $match[0];
}
}
我為可能給您帶來的麻煩感到抱歉,我想在沒有preg_split()函數的情況下這樣做是因為我以為preg_split()無法返回它返回的字符串的strpos,但一直以來,這僅僅是一件事情像這樣$Array = preg_split('/<[^>]*>/', $string, 0, PREG_SPLIT_OFFSET_CAPTURE);
得到我想要的。 我只希望能夠從字符串中提取strpos以及字符串。 我喜歡這個網站如何擁有如此有用的社區,非常感謝大家的幫助,我非常感謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.