I'm trying to use preg_match to grab the text in between two HTML tags.
Here's a simplified version of my code:
$sPattern = "/<li class=\"sample\">(.*?)<\/li>/s";
$sText = "blah blah blah <li class=\"sample\">hello world!</li> blah blah blah";
preg_match($sPattern,$sText,$aMatch);
echo '<pre>'.print_r($aMatch).'</pre>';
However, when I run this code, I get the full HTML string returned:
<li class=\"sample\">hello world!</li>
Does anyone know what changes I need to make to my regular expression?
Note: I'm aware of other ways to parse data from an HTML page. For various reasons, DOMDocument and DOMXPath are not an option--I'm sticking with RegEx.
This should work how you want:
$sPattern = "/<li class=\"sample\">(.*?)<\/li>/s";
$sText = "blah blah blah <li class=\"sample\">hello world!</li> blah blah blah";
preg_match($sPattern,$sText,$aMatch);
echo '<pre>'.$aMatch[1].'</pre>';
You need to access the capturing group output.
var_dump( $aMatch[1]);
Here is a demo showing that the regex is working fine, you're just accessing the resulting array incorrectly.
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.