尝试使用解析器:
require_once "simple_html_dom.php";
$text = 'foo
$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";
}
}
输出:
编辑:更多为了我自己的娱乐我试图在正则表达式.这就是我想出的:
$text = 'foo
baz
if(preg_match_all('#
print_r($matches[0]);
}
输出:
Array
(
[0] =>
[1] =>
)
还有一个小解释:
[^<>]* # match zero or more chars other than ''
( # open group 1
(?: # open a non-matching group
[^<>]* # match zero or more chars other than ''
| # OR
(?1) # recursively match what is defined by group 1
)* # close the non-matching group and repeat it zero or more times
) # close group 1
[^<>]* # match zero or more chars other than ''
现在也许你理解为什么人们试图说服你不要使用正则表达式.正如已经指出的那样,如果html格式不正确,它将无济于事:正如我所向你保证的那样,正则表达式会使输出变得比html解析器更大.此外,正则表达式可能会让你的眼睛流血,你的同事(或维护你的软件的人)可能会在看到你做了什么后来找你. 🙂
最好的办法是首先清理输入(使用TIDY或类似的),然后使用解析器获取所需的信息.