regex php: find everything in div

好久不见. 提交于 2019-12-17 16:51:08

问题


I'm trying to find eveything inside a div using regexp. I'm aware that there probably is a smarter way to do this - but I've chosen regexp.

so currently my regexp pattern looks like this:

$gallery_pattern = '/<div class="gallery">([\s\S]*)<\/div>/';  

And it does the trick - somewhat.

The problem is if i have two divs after each other - like this.

<div class="gallery">text to extract here</div>
<div class="gallery">text to extract from here as well</div>

I want to extract the information from both divs, but my problem, when testing, is that im not getting the text in between as a result but instead:

"text to extract here </div>  
<div class="gallery">text to extract from here as well"

So to sum up. It skips the first end of the div. and continues on to the next. The text inside the div can contain <, / and linebreaks. just so you know!

Does anyone have a simple solution to this problem? Im still a regexp novice.


回答1:


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 ?




回答2:


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>';
    }
}



回答3:


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



来源:https://stackoverflow.com/questions/1352078/regex-php-find-everything-in-div

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