尝试使用解析器代替:
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";
}
}
Output:
<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]);
}
Output:
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'
现在也许你明白为什么人们试图说服你not为此使用正则表达式。正如已经指出的,如果 html 格式不正确,那将无济于事:我向你保证,正则表达式将比 html 解析器造成更大的输出混乱。此外,正则表达式可能会让您流血,您的同事(或维护您的软件的人)可能会在看到您所做的事情后来找您。 :)
你最好的选择是首先清理你的输入(使用TIDY或类似的),然后使用解析器来获取您想要的信息。