regex php: find everything in div

拥有回忆 提交于 2019-11-28 01:31:53

What about something like this :

$str = <<<HTML
<div class="gallery">text to extract here</div>
<div class="gallery">text to extract from here as well</div>
HTML;

$matches = array();
preg_match_all('#<div[^>]*>(.*?)</div>#', $str, $matches);

var_dump($matches[1]);

Note the '?' in the regex, so it is "not greedy".

Which will get you :

array
  0 => string 'text to extract here' (length=20)
  1 => string 'text to extract from here as well' (length=33)

This should work fine... If you don't have imbricated divs ; if you do... Well... actually : are you really sure you want to use rational expressions to parse HTML, which is quite not that rational itself ?

You shouldn't be using regex to parse HTML when there's a convenient DOM library:

$str = '
<div class="gallery">text to extract here</div>
<div class="gallery">text to extract from here as well</div>
';

$doc = new DOMDocument();
$doc->loadHTML($str);
$divs = $doc->getElementsByTagName('div');

if ( count($divs ) ) {
    foreach ( $divs as $div ) {
    echo $div->nodeValue . '<br>';
    }
}

A possible answer to this problem can be found at http://simplehtmldom.sourceforge.net/ That class help me to solve similar problem quickly

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