我想將長文本分成塊。我需要按元素類進行拆分(元素可以是 h、p、span、div 或其他未知標簽)。因此,例如,如果我得到一個字串,例如:
$string = 'Hi this is a long <span >string</span> and I need to <span >split it into chunks</span> and I need help for <span >this</span>';
我想按cut類拆分成陣列,保留所有文本:預期結果:
$array(
0 => 'Hi this is a long ',
1 => '<span >string</span>',
2 => ' and I need to ',
3 => '<span >split it into chunks</span>',
4 => ' and I need help for ',
5 => '<span >this</span>'
);
我在網上找不到任何示例。
我只找到這個,它只按類查找元素并排除所有其他文本,我不知道它是否對我的目的有用:
$domdocument = new DOMDocument();
$domdocument->loadHTML($contenuto);
$a = new DOMXPath($domdocument);
$elements = $a->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' cut')]");
for ($i = $elements->length - 1; $i > -1; $i--) {
var_dump($elements->item($i)->firstChild->nodeValue);
}
uj5u.com熱心網友回復:
我們可以preg_match_all在這里嘗試正則運算式匹配所有方法:
$string = 'Hi this is a long <span >string</span> and I need to <span >split it into chunks</span> and I need help for <span >this</span>';
preg_match_all("/<(\w ).*?>.*?<\/\\1>|.*?(?=<|$)/", $string, $matches);
$lines = $matches[0];
array_pop($lines);
print_r($lines);
這列印:
Array
(
[0] => Hi this is a long
[1] => <span class="cut">string</span>
[2] => and I need to
[3] => <span class="cut">split it into chunks</span>
[4] => and I need help for
[5] => <span class="cut">this</span>
)
此處使用的正則運算式模式表示匹配:
<(\w ).*?> an HTML tag
.*? any content
<\/\\1> closing tag
| OR
.*? any other content until reaching, but not including
(?=<|$) the next HTML tag or the end of the input
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/464635.html
標籤:php
下一篇:紅日靶場七——WP
