正则表达式来获取PHP中2个标签的文本

正则表达式来获取PHP中2个标签的文本

问题描述:

I have string like

<li class="video_description"><strong>Description:</strong> hello world, This is test description.</li>

And i want string like, "hello world, This is test description." That string willbe dynamic everytime.

So, how i can use preg_match option here?

It is not a good idea to use regex to parse html in PHP.

I would suggest to use simple_html_dom as it is simple and suits your situation

With all the disclaimers about using regex to parse html, if you want a regex, you can use this:

>\s*\K(?:(?!<).)+(?=</li)

See the match in the Regex Demo.

Sample PHP Code

$regex = '~>\s*\K(?:(?!<).)+(?=</li)~';
preg_match_all($regex, $yourstring, $matches);
print_r($matches[0]);

Explanation

  • >\s* matches a closing > and optional spaces
  • The \K tells the engine to drop what was matched so far from the final match it returns
  • (?:(?!<).)+ matches any chars that do not start a tag
  • The lookahead (?=</li) asserts that what follows is </li

Another solution

<li.*<\/strong>\s?(.*)<\/li>

Usage:

$string = '<li class="video_description"><strong>Description:</strong> hello world, This is test description.</li>';
$pattern = '/<li.*<\/strong>\s?(.*)<\/li>/';
if(preg_match($pattern, $string)){
  echo "Macth was found";
}