tags:

views:

38

answers:

3

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.

A: 

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

Shadow
+4  A: 
<?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
Using DOM is the correct way to parse this, regex is a bandaid.
TravisO
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
@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
A: 

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