简体   繁体   English

使用正则表达式从php中的字符串中选择html标签的一部分

[英]use regular expression to select part of html tag from string in php

I would like to select the string in a div tag in php. 我想在php的div标签中选择字符串。 I plan to do it with regular expression. 我打算用正则表达式来做。 But is there a better way? 但是有更好的方法吗?

Like this: Hello there <div>how are you?</div>. Please <div>send my regards</div> to Allan. 像这样: Hello there <div>how are you?</div>. Please <div>send my regards</div> to Allan. Hello there <div>how are you?</div>. Please <div>send my regards</div> to Allan.

I would like to retrieve all texts in and together with div tag like: 我想检索所有文本以及div标签,例如:

"<div>how are you?</div>"
"<div>send my regards</div>"

May I know how to do? 我可以知道怎么做吗?

I plan to do it with regular expression. 我打算用正则表达式来做。

Nope , don't do that. 不,不要那样做。 The concrete reason here 这里的具体原因

But is there a better way? 但是有更好的方法吗?

Yes , use a DOM Parser for this .. 是的,为此使用DOM Parser

$html='Hello there <div>how are you?</div>. Please <div>send my regards</div> to Allan.';
$dom = new DOMDocument;
$dom->loadHTML($html);
$divText='';
foreach ($dom->getElementsByTagName('div') as $tag) {
      $divText.=$dom->saveHTML($tag);
}
echo $divText;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM