rajan
rajan

Reputation: 1

How to find content using PHP regular expression

I want to find content inside of a DIV. I just want to specify the DIV’s id; the rest is automatically adjusted under preg_match. E.g.:

<div id="midbuttonarea" etc...>some text...</div>

Upvotes: 0

Views: 2270

Answers (2)

Brenton Alker
Brenton Alker

Reputation: 9072

You're much more likely to get a good result using an HTML parser to parse HTML instead of Regex. It's extremely difficult to parse HTML with Regex, and the result may not be very reliable.

Check the accepted answer to this question: How do you parse and process HTML/XML in PHP? for some suggestions on how to go about it.

Upvotes: 1

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18344

Brenton is right. Anyway, here you have:

<?php
   function findDivInnerHtml($html, $id){
      preg_match("/<div .* id=\"{$id}\" .*>(.*)<\\/div>/i", $html, $matches);
      return $matches[1];
   }
?>

Sample usage:

<?php
   $html = '<div id="other"> xxx </div>  <div id="midbuttonarea" etc...>some text...</div> ';
   $innerHTML = findDivInnerHtml($html, 'midbuttonarea');       
   echo $innerHTML; //outputs "some text..."
?>

Hope this helps.

Upvotes: 1

Related Questions