Search code examples
phpregexhtml-parsingpreg-match-all

Extract img src from string with preg_match_all


I've been trying to use preg_match_all for 30 minutes but it looks like I can't do it.

Basically I have a $var which contains a string of HTML code. For example:

<br>iihfuhuf
<img title="Image: http://www.jlnv2.local/temp/temp513caca536fcd.jpeg"   
 src="http://www.jlnv2.local/temp/temp513caca536fcd.jpeg">
<img src="http://www.jlnv2.local/temp/temp513caca73b8da.jpeg"><br>

I want to get the src attribute values of img tags that contain /temp/temp[a-z0-9]{13}\.jpeg in their src value.

This is what I have so far:

preg_match_all('!(<img.*src=".*/temp/temp[a-z0-9]{13}\.jpeg"(.*alt=".*")?>)!', $content, $matches);

Solution

  • <img[^>]*src="([^"]*/temp/temp[a-z0-9]{13}\.jpeg)"
    

    <img[^>]* Select IMG tags

    src="([^"]*)" gets src value and save it as a match

    /temp/temp[a-z0-9]{13}\.jpeg is the filter for src values

    For quick RegEx tests use some online tool like http://regexpal.com/