kongar
kongar

Reputation: 53

preg_match() not matching img src

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

Answers (1)

John Conde
John Conde

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

Demo

Upvotes: 1

Related Questions