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

我正在尝试使用 regexp在div中找到eveything.我知道可能有一种更聪明的方法 – 但我选择了regexp.

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

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

它有点诀窍.

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

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

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

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

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

解决方法

这样的事情怎么样:

$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]);

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

哪个会给你:

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

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

相关文章

jquery.validate使用攻略(表单校验) 目录 jquery.validate...
/\s+/g和/\s/g的区别 正则表达式/\s+/g...
自整理几个jquery.Validate验证正则: 1. 只能输入数字和字母...
this.optional(element)的用法 this.optional(element)是jqu...
jQuery.validate 表单动态验证 实际上jQuery.validate提供了...
自定义验证之这能输入数字(包括小数 负数 ) &lt;script ...