Skip to content Skip to sidebar Skip to footer

Regular Expression In Php To Return Array With All Images From Html, Eg: All Src="images/header.jpg" Instances

I'd like to be able to return an array with a list of all images (src='' values) from html [0] = 'images/header.jpg' [1] = 'images/person.jpg' is there a regular expression th

Solution 1:

Welcome to the world of the millionth "how to exactract these values using regex" question ;-) I suggest to use the search tool before seeking an answer -- here is just a handful of topics that provide code to do exactly what you need;

Solution 2:

/src="([^"]+)"/

The image will be in group 1.

Example:

preg_match_all('/src="([^"]+)"/', '<imgsrc="lol"><imgsrc="wat">', $arr, PREG_PATTERN_ORDER);

Returns:

Array
(
    [0] => Array
        (
            [0] => src="lol"
            [1] => src="wat"
        )

    [1] => Array
        (
            [0] => lol
            [1] => wat
        )

)

Solution 3:

Here is a more polished version of the regular expression provided by Håvard:

/(?<=src=")[^"]+(?=")/

This expression uses Lookahead & Lookbehind Assertions to get only what you want.

$str = '<img src="/img/001.jpg"><img src="/img/002.jpg">';

preg_match_all('/(?<=src=")[^"]+(?=")/', $str, $srcs, PREG_PATTERN_ORDER);

print_r($srcs);

The output will look like the following:

Array
(
    [0] => Array
        (
            [0] => /img/001.jpg
            [1] => /img/002.jpg
        )

)

Solution 4:

I see that many peoples struggle with Håvard's post and <script> issue. Here is same solution on more strict way:

<img.*?src="([^"]+)".*?>

Example:

preg_match_all('/<img.*?src="([^"]+)".*?>/', '<imgsrc="lol"><imgsrc="wat">', $arr, PREG_PATTERN_ORDER);

Returns:

Array
(
    [1] => Array
        (
            [0] => "lol"
            [1] => "wat"
        )

)

This will avoid other tags to be matched. HERE is example.

Post a Comment for "Regular Expression In Php To Return Array With All Images From Html, Eg: All Src="images/header.jpg" Instances"