正则表达式php:在div中找到所有内容

前端之家收集整理的这篇文章主要介绍了正则表达式php:在div中找到所有内容前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用 regexp在div中找到eveything.我知道可能有一种更聪明的方法 – 但我选择了regexp.

所以目前我的正则表达式模式如下:

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

它有点诀窍.

问题是如果我有两个divs – 像这样.

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

我想从两个div中提取信息,但是在测试时我的问题是我没有在文本之间得到结果,而是:

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

所以总结一下.它会跳过div的第一端.并继续下一个.
div中的文本可以包含<,/和换行符.只是你知道! 有没有人有这个问题的简单解决方案?我仍然是一个正则表达新手.

解决方法

这样的事情怎么样:

  1. $str = <<<HTML
  2. <div class="gallery">text to extract here</div>
  3. <div class="gallery">text to extract from here as well</div>
  4. HTML;
  5.  
  6. $matches = array();
  7. preg_match_all('#<div[^>]*>(.*?)</div>#',$str,$matches);
  8.  
  9. var_dump($matches[1]);

注意’?’在正则表达式中,所以它“不贪心”.

哪个会给你:

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

这应该可以正常工作……如果你没有瓦片化的div;如果你这样做……嗯……实际上:你真的确定要使用理性表达式解析HTML,这本身就不那么理性吗?

猜你在找的正则表达式相关文章