如何使用正则表达式从HTML获取字符串? [英] How to get string from HTML with regex?

查看:89
本文介绍了如何使用正则表达式从HTML获取字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从html页面解析块,所以我尝试使用php preg_match此块

I'm trying to parse block from html page so i try to preg_match this block with php

if( preg_match('<\/div>(.*?)<div class="adsdiv">', $data, $t)) 

但不起作用

</div>

blablabla

blablabla

blablabla

<div class="adsdiv">

我只希望grep blablabla blablabla个字 任何帮助

i want grep only blablabla blablabla words any help

推荐答案

除上述内容外,还添加/s修饰符,以便.匹配换行符. (正如Alan所指出的,[^<]+仍将与换行符匹配)

Apart from what has been said above, also add the /s modifier so . will match newlines. (edit: as Alan kindly pointed out, [^<]+ will match newlines anyway)

我也总是使用/U,因为在这些情况下,默认情况下通常需要最小的匹配. (速度也会更快).还有/i,因为人们会说<div><DIV>甚至是<Div> ...

I always use /U as well since in these cases you normally want minimal matching by default. (will be faster as well). And /i since people say <div>, <DIV>, or even <Div>...

if (preg_match('/<\/div>([^<]+)<div class="adsdiv">/Usi', $data, $match))
{
    echo "Found: ".$match[1]."<br>";
} else {
    echo "Not found<br>";
}

修改使它更加明确!

这篇关于如何使用正则表达式从HTML获取字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆