Zia
Zia

Reputation: 2710

extract two parts of a string using regex in php

I have this string:

  <img src=images/imagename.gif alt='descriptive text here'>

and I am trying to split it up into the following two strings (array of two strings, what ever, just broken up).

  imagename.gif
  descriptive text here

Note that yes, it's actually the &lt; and not <. Same with the end of the string.

I know regex is the answer, but I'm not good enough at regex to know how to pull it off in PHP.

Upvotes: 1

Views: 222

Answers (2)

GBD
GBD

Reputation: 15981

Better use DOM xpath rather than regex

<?php
$your_string = html_entity_decode("&lt;img src=images/imagename.gif alt='descriptive text here'&gt;");
$dom = new DOMDocument;
$dom->loadHTML($your_string);
$x = new DOMXPath($dom); 

foreach($x->query("//img") as $node) 
{
    echo $node->getAttribute("src");
    echo $node->getAttribute("alt");
}

?>

Upvotes: 2

ghoti
ghoti

Reputation: 46886

Try this:

<?php

$s="&lt;img src=images/imagename.gif alt='descriptive text here'&gt;";

preg_match("/^[^\/]+\/([^ ]+)[^']+'([^']+)/", $s, $a);

print_r($a);

Output:

Array
(
    [0] => &lt;img src=images/imagename.gif alt='descriptive text here
    [1] => imagename.gif
    [2] => descriptive text here
)

Upvotes: 2

Related Questions