Capture the image link contained in html

Asked

Viewed 79 times

2

I have the following code:

<?php
$content = '
text text text text <img src="path/to/image/1">text text text text
    <img src="path/to/image/2">
text text text text text text text text text text text text text text text text <img src="path/to/image/3"><img src$
<img src="path/to/image/5"> ';

$frst_image = preg_match_all( '|<img.*?src=[\'"](.*?)[\'"].*?>|i', $content, $matches );

print_r($matches[0]);

He is returning:

Array
(
    [0] => <img src="path/to/image/1">
    [1] => <img src="path/to/image/2">
    [2] => <img src="path/to/image/3">
    [3] => <img src="path/to/image/4">
    [4] => <img src="path/to/image/5">
)

However, I want you to return only the content contained within src, how do I do that?

  • http://stackoverflow.com/questions/887307/getting-href-value-of-from-a-tag

  • I need it done in the back-end

2 answers

4


Just use the right index:

print_r( $matches[1] );

See working on IDEONE.

You used the index 0, that represents the whole captured set. The 1 henceforth represent the catch groups in parentheses, which is what you need.

  • My ugly mania to complicate things +1

  • inattention of mine, confused head from so much fatigue. Thank you

  • @Gabrielrodrigues was a good addition to yours, can serve for more complex things.

  • @Fábio when you use print_r, can help test without index, print_r( $matches );, so it becomes easier to see the whole structure of the variable.

4

Browser other questions tagged

You are not signed in. Login or sign up in order to post.