0

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.

1
  • There is no g global flag in PHP. Use preg_match_all for getting all matches. Further your pattern would match images/Christmas.PNG" width=70%; height=40%" probably you wanted <img src="([^"]+) Dec 29, 2020 at 3:21

1 Answer 1

1

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

4
  • When I use this, it doesn't echo anything on my screen.
    – kongar
    Dec 29, 2020 at 0:58
  • You should as this works for PHP versions all the way back to 5.1. Make sure you don't have a syntax error in your code.
    – John Conde
    Dec 29, 2020 at 1:00
  • thanks i had it before it was initialised. The reason i wanted strpos was i need the index of the substring (the first index). How can I do that?
    – kongar
    Dec 29, 2020 at 1:05
  • I'm away from a computer right now but something like $position = strpos($string, 'src'); should do the trick.
    – John Conde
    Dec 29, 2020 at 1:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.