Capture the link of images contained in html

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]);

It 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 to return only content contained within src , how do I do this?

    
asked by anonymous 21.03.2016 / 14:32

2 answers

4

Just use the correct index:

print_r( $matches[1] );

See working at IDEONE .

You used the index 0 , which represents the whole captured set. The indexes of 1 onwards represent the capture groups in parentheses, which is what you need.

    
21.03.2016 / 14:48
4

You can use DOMDocument () and simplexml_import_dom () loop through the src attribute.

Example:

$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br><img src=\"myimage.jpg\" title=\"title\" alt=\"alt\"></body></html>");
$xml = simplexml_import_dom($doc);
$images = $xml->xpath('//img');
foreach ($images as $img) {
   echo $img['src'];
}

Exit:

myimage.jpg

See working at ideone

Reference and more examples: How to extract img src, title and alt from html using php?

    
21.03.2016 / 14:50