1

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" height="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.

babadbee
  • 863
  • 5
  • 14
  • 18
  • Although you are trying to get those values from PHP code/src how do you want to implement the solution? – Kaili Jul 07 '10 at 21:02
  • possible duplicate of [How to extract img src, title and alt from html using php?](http://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php) – Gordon Jul 07 '10 at 21:27

3 Answers3

4
<?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
)
Artefacto
  • 96,375
  • 17
  • 202
  • 225
  • Using DOM is the correct way to parse this, regex is a bandaid. – TravisO Jul 07 '10 at 21:07
  • normally I'd agree, but not in this case - he has a very simple string, not a full DOM or even partial DOM serialized in a chunk of (x)HTML - it may /look/ like it, but it's not - regex is the effective way to handle this, DOM on this occasion is overkill – nathan Jul 08 '10 at 10:47
  • @nathan By that logic, `$res=array("image1.gif", "image3.gif", "image2.gif")` is also a valid solution. You're reading the question too narrowly, you need to generalize the example given the OP to other situations and, for general HTML, regex doesn't work. – Artefacto Jul 08 '10 at 10:57
0

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)?

Kaili
  • 1,208
  • 9
  • 20
0

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

:)

nathan
  • 5,402
  • 1
  • 22
  • 18
  • Ah ha thanks! I didnt expect a complete function, but I knew it would be to do with regular expressions...which I am horrific at! Thank you. – babadbee Jul 08 '10 at 08:08