[英]PHP RegExp for nested Div tags
我需要一個可以與 PHP 的 preg_match_all() 一起使用的正則表達式來匹配 div 標簽中的內容。 div 看起來像這樣:
<div id="t1">Content</div>
到目前為止,我已經提出了這個正則表達式,它匹配了 id="t[number]" 的所有 div
/<div id="t(\\d)">(.*?)<\\/div>/
問題是當內容包含更多 div 時,嵌套的 div 如下所示:
<div id="t1">Content <div>more stuff</div></div>
關於如何使我的正則表達式與嵌套標簽一起工作的任何想法?
謝謝
嘗試使用解析器:
require_once "simple_html_dom.php";
$text = 'foo <div id="t1">Content <div>more stuff</div></div> bar <div>even more</div> baz <div id="t2">yes</div>';
$html = str_get_html($text);
foreach($html->find('div') as $e) {
if(isset($e->attr['id']) && preg_match('/^t\d++/', $e->attr['id'])) {
echo $e->outertext . "\n";
}
}
輸出:
<div id="t1">Content <div>more stuff</div></div>
<div id="t2">yes</div>
在此處下載解析器: http : //simplehtmldom.sourceforge.net/
編輯:更多為了我自己的娛樂,我試圖用正則表達式來做。 這是我想出的:
$text = 'foo <div id="t1">Content <div>more stuff</div></div> bar <div>even more</div>
baz <div id="t2">yes <div>aaa<div>bbb<div>ccc</div>bbb</div>aaa</div> </div>';
if(preg_match_all('#<div\s+id="t\d+">[^<>]*(<div[^>]*>(?:[^<>]*|(?1))*</div>)[^<>]*</div>#si', $text, $matches)) {
print_r($matches[0]);
}
輸出:
Array
(
[0] => <div id="t1">Content <div>more stuff</div></div>
[1] => <div id="t2">yes <div>aaa<div>bbb<div>ccc</div>bbb</div>aaa</div> </div>
)
和一個小解釋:
<div\s+id="t\d+"> # match an opening 'div' with an id that starts with 't' and some digits
[^<>]* # match zero or more chars other than '<' and '>'
( # open group 1
<div[^>]*> # match an opening 'div'
(?: # open a non-matching group
[^<>]* # match zero or more chars other than '<' and '>'
| # OR
(?1) # recursively match what is defined by group 1
)* # close the non-matching group and repeat it zero or more times
</div> # match a closing 'div'
) # close group 1
[^<>]* # match zero or more chars other than '<' and '>'
</div> # match a closing 'div'
現在也許您明白為什么人們試圖說服您不要為此使用正則表達式。 如前所述,如果 html 格式不正確,這將無濟於事:我向您保證,正則表達式會比 html 解析器造成更大的輸出混亂。 此外,正則表達式可能會讓您眼花繚亂,您的同事(或將維護您的軟件的人)可能會在看到您所做的事情后來找您。 :)
最好的辦法是首先清理你的輸入(使用TIDY或類似的),然后使用解析器來獲取你想要的信息。
如果你相信這個人,至少有一個正則表達式可以解決這個問題,他說它比 dom 方法更快......我同意他的看法。
http://www.php.net/manual/fr/regexp.reference.recursive.php#95568
$pattern = "/<([\w]+)([^>]*?) (([\s]*\/>)| (>((([^<]*?|<\!\-\-.*?\-\->)| (?R))*)<\/\\1[\s]*>))/xsm";
我認為使用一些DOM 工具會更好
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.