Regular expression to extract content from a div w

2019-07-29 15:24发布

问题:

I want to extract content from a div whose id starts with a specific string, but ends with anything. Example:

I have a div

<div id="content_message_56384">
  My first post.
</div>

My code:

$regex = '#\<div id="content_message_[*]"\>(.+?)\<\/div\>#s';
preg_match($regex, $intro, $matches);
echo $match = $matches[0];

But I'm not not getting any result. Please help.

回答1:

The code should be this:

$string = "<div id=\"content_message_56384\">
  My first post.
</div>";
$regex = '/<div id="content_message_(?:\d+)">(.+?)<\/div>/s';
preg_match($regex, $string, $matches);
print($maches[1]);

Please, note that I'm using a non-capturing expression here (?:\d+) because you only need what's inside the <div>.



回答2:

$intro='<div id="content_message_56384">
  My first post.
</div><div id="content_message_5577577IIRRIR">
  My second possssss.
</div>';
$regex = '#\<div id="content_message_+.+"\>(.+?)\<\/div\>#s';
preg_match($regex, $intro, $matches);
print_r($matches[0]);