Regular expression to extract content from a div w

2019-07-29 15:19发布

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.

2条回答
我命由我不由天
2楼-- · 2019-07-29 16:05
$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]);
查看更多
孤傲高冷的网名
3楼-- · 2019-07-29 16:08

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

查看更多
登录 后发表回答