php preg match all, all the `p`

半城伤御伤魂 提交于 2020-02-06 09:25:52

问题


<?php
$str= <<<ETO
<p>one
two</p>
<p>three</p>
ETO;
preg_match_all('/<p>(.*?)<\/p>/',$str,$r);
print_r($r);
?>

I am studying preg_match_all. I want get all the p from one article. but my code only get the second p. how to modify so that I can get the first p, either. Thanks.


回答1:


You are missing the /ims flag at the end of your regex. Otherwise . will not match line breaks (as in your first paragraph). Actually /s would suffice, but I'm always using all three for simplicity.

Also, preg_match works for many simple cases. But if you are attempting any more complex extractions, then consider alternating to phpQuery or QueryPath which allow for:

foreach (qp($html)->find("p") as $p)  { print $p->text(); }



回答2:


(.*?) is not matching newline characters. Try the /s modifier:

<?php
$str= <<<ETO
<p>one 
two</p>
<p>three</p>
ETO;
preg_match_all('/<p>(.*?)<\/p>/s',$str,$r);
print_r($r);
?>


来源:https://stackoverflow.com/questions/5376512/php-preg-match-all-all-the-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!