php 嵌套div,嵌套Div标签的PHP RegExp

尝试使用解析器:

require_once "simple_html_dom.php";

$text = 'foo

Content
more stuff
bar
even more
baz
yes
';

$html = str_get_html($text);

foreach($html->find('div') as $e) {

if(isset($e->attr['id']) && preg_match('/^t\d++/', $e->attr['id'])) {

echo $e->outertext . "\n";

}

}

输出:

Content
more stuff
yes

编辑:更多为了我自己的娱乐我试图在正则表达式.这就是我想出的:

$text = 'foo

Content
more stuff
bar
even more

baz

yes
aaa
bbb
ccc
bbb
aaa
';

if(preg_match_all('#

[^<>]*(
]*>(?:[^<>]*|(?1))*
)[^<>]*
#si', $text, $matches)) {

print_r($matches[0]);

}

输出:

Array

(

[0] =>

Content
more stuff

[1] =>

yes
aaa
bbb
ccc
bbb
aaa

)

还有一个小解释:

# match an opening 'div' with an id that starts with 't' and some digits

[^<>]* # match zero or more chars other than ''

( # open group 1

]*> # match an opening 'div'

(?: # open a non-matching group

[^<>]* # match zero or more chars other than ''

| # OR

(?1) # recursively match what is defined by group 1

)* # close the non-matching group and repeat it zero or more times

# match a closing 'div'

) # close group 1

[^<>]* # match zero or more chars other than ''

# match a closing 'div'

现在也许你理解为什么人们试图说服你不要使用正则表达式.正如已经指出的那样,如果html格式不正确,它将无济于事:正如我所向你保证的那样,正则表达式会使输出变得比html解析器更大.此外,正则表达式可能会让你的眼睛流血,你的同事(或维护你的软件的人)可能会在看到你做了什么后来找你. 🙂

最好的办法是首先清理输入(使用TIDY或类似的),然后使用解析器获取所需的信息.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值