Reputation: 53
I have this string in a php variable.
$str = 'This is an iamge: <img src="images/Christmas.PNG" width=70%; height=40%">';
The pattern I am searching:
$pattern = '/<img src="(.*?)>/g';
I then have this preg_match()
preg_match($pattern, $str, $matches, PREG_OFFSET_CAPTURE);
When i go to print $matches
either directly by echo $matches
or in a foreach loop, the variable is null.
Why is this happening? Thanks.
Upvotes: 0
Views: 58
Reputation: 219864
Don't use regexes for parsing HTML. There are tools designed for this very thing.
You can use DOMDocument
to parse the HTML and then easily get the value of the src
attribute:
$previous_value = libxml_use_internal_errors(true);
$string = 'This is an iamge: <img src="images/Christmas.PNG" width=70%; height=40%">';
$dom = new DOMDocument();
$dom->loadHTML($string);
echo $dom->getElementsByTagName('img')->item(0)->getAttribute("src");
libxml_clear_errors();
libxml_use_internal_errors($previous_value);
Upvotes: 1