简体   繁体   中英

Regular expression to extract content from a div whose id starts with a specifc string

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.

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

$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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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