加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:39:22 所属栏目:百科 来源:网络整理
导读:我正在尝试使用 regexp在div中找到eveything.我知道可能有一种更聪明的方法 – 但我选择了regexp. 所以目前我的正则表达式模式如下: $gallery_pattern = '/div class="gallery"([sS]*)/div/'; 它有点诀窍. 问题是如果我有两个divs – 像这样. div class=
我正在尝试使用 regexp在div中找到eveything.我知道可能有一种更聪明的方法 – 但我选择了regexp.

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

$gallery_pattern = '/<div class="gallery">([sS]*)</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,这本身就不那么理性吗?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读