从PHP中的字符串中获取多个图像src

$string = "<p>dsaasdsdsdas sdhio ahsas asdsad adhaso img da sda a asd a as src asdasd ds.</p>   <p>dsaasdsdsdas sdhio ahsas asdsad adhaso img da sda a asd a as src asdasd ds.</p>  <p>dsaasdsdsdas <img src='http://stie.com/teste.jpg'> ds.</p>   <p>dsaasdsdsdas sdhio ahsas asdsad adhaso img da sda a asd <img src='http://segunda.com/teste.jpg'> a as src asdasd ds.</p>     <p>dsaasdsdsdas sdhio ahsas asdsad adhaso img da sda a asd a as src asdasd ds.</p>";

$doc = new DOMDocument();   
$doc->loadHTML($string);    
$xpath = new DOMXPath($doc);    
$src = $xpath->evaluate("string(//img/@src)");

echo $src;

I have this code to try to extract all img sources from a string in PHP. But my code have an issue, if it has more than one image, it only get the first image src. How can I change this to give me all image src in a string, to an array for example?

 preg_match('/< *img[^>]*src *= *["\']?([^"\']*)/i', $yourDomString, $matches);
print_r($matches); //returns all SRC results of img tags.

know more about preg_match

The problem is not in your PHP code, it is a peculiarity of XPath 1.0 (which your library uses). If you use a function like string() on a set of nodes, the function will only be applied to the first item and all others will be ignored.

Instead of looking for string(//img/@src), select all img elements in a first step and only then retrieve their src attribute values with getAttribute().

PHP

<?php

$string = "<p>dsaasdsdsdas sdhio ahsas asdsad adhaso img da sda a asd a as src asdasd ds.</p>   <p>dsaasdsdsdas sdhio ahsas asdsad adhaso img da sda a asd a as src asdasd ds.</p>  <p>dsaasdsdsdas <img src='http://stie.com/teste.jpg'> ds.</p>   <p>dsaasdsdsdas sdhio ahsas asdsad adhaso img da sda a asd <img src='http://segunda.com/teste.jpg'> a as src asdasd ds.</p>     <p>dsaasdsdsdas sdhio ahsas asdsad adhaso img da sda a asd a as src asdasd ds.</p>";

$doc = new DOMDocument();   
$doc->loadHTML($string);    
$xpath = new DOMXPath($doc);    
$images = $xpath->evaluate("//img");

foreach ($images as $image) {
    $src = $image->getAttribute('src');
    echo $src;
    echo "
";
}

?>

Output

http://stie.com/teste.jpg
http://segunda.com/teste.jpg

Please note: parsing an HTML string with regular expressions, as the other answer suggests, is not a good idea in most cases.