Getting the src of a list of images PHP
I know it sounds a bit odd but I have a string:
<img src="image1.gif" width="20" height="20"><img src="image3.gif" width="20" hei开发者_运维问答ght="20"><img src="image2.gif" width="20" height="20">
Is there a easy way to get this into an array of
array('image1.gif','image3.gif','image2.gif');
Thanks.
<?php
$xml = <<<XML
<img src="image1.gif" width="20" height="20">
<img src="image3.gif" width="20" height="20">
<img src="image2.gif" width="20" height="20">
XML;
libxml_use_internal_errors(true);
$d = new DOMDocument();
$d->loadHTML($xml);
$res = array();
foreach ($d->getElementsByTagName("img") as $e) {
$res[] = $e->getAttribute("src");
}
print_r($res);
gives
Array ( [0] => image1.gif [1] => image3.gif [2] => image2.gif )
yes
function get_image_sources( $s )
{
preg_match_all( '/src="([^"]+)"/i' , $s , $sources );
if(!(count($sources) == 2) || !count($sources[1]) ) return array();
return $sources[1];
}
:)
Use a regular expression to extract each of the items into an array or string.
Sounds like a homework problem I had once back in the day anyway, this should get you close...
src\s*=\s*([\'"])?([^\'" >]+)(\1)?
精彩评论