1

I would like to select the string in a div tag in php. 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.

I would like to retrieve all texts in and together with div tag like:

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

May I know how to do?

davidlee
  • 5,611
  • 17
  • 56
  • 82
  • 1
    http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Andresch Serj May 06 '14 at 06:57
  • possible duplicate of [How do you parse and process HTML/XML in PHP?](http://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php) – HamZa May 08 '14 at 19:13

1 Answers1

1

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 ..

$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;
Community
  • 1
  • 1
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126