0

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 that can do this?

Many thanks in advance!

1

4 Answers 4

3

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;

Sign up to request clarification or add additional context in comments.

1 Comment

And regular expressions are not a solution for this.
1

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

The image will be in group 1.

Example:

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

Returns:

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

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

)

1 Comment

<script src="foo.js"></script> — Regular expressions do not play well with HTML, overly simplistic regular expressions less so.
1

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
        )

)

1 Comment

using src regex get js also in my case ( for example : [28] => /modules/jcarousel/assets/carousel_start.js )
1

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="([^"]+)".*?>/', '<img src="lol"><img src="wat">', $arr, PREG_PATTERN_ORDER);

Returns:

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

)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.