我需要一个可以与 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 或类似的),然后使用解析器来获取你想要的信息。
关于用于嵌套 Div 标签的 PHP RegEx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1721223/