3

From a string such as this <img src="/images/mylondon.jpg" /> I'm trying to retrieve JUST the url for use elsewhere in PHP

I know Regular expressions are the way to go, but I can't get my head around them right now.

Could anyone be of assistance?

2
  • I've used the answer given below, which works, but is there a better way of doing this? It's not an entire document I'm searching through, just a couple of lines of HTML... Commented Sep 18, 2011 at 14:22
  • "Regular expressions are the way to go" Somebody has been deceiving you. Regular expressions are only an acceptable way for regular languages. For the other languages, they can create massive problems. See also stackoverflow.com/questions/1732348/… Commented Sep 18, 2011 at 15:38

2 Answers 2

8
preg_match_all('~<img.*?src=["\']+(.*?)["\']+~', $html, $urls);
$urls = $urls[1]
Sign up to request clarification or add additional context in comments.

11 Comments

This regular expression won't work in a lot of situations. And as always, it's a bad idea to use regular expressions with HTML.
What would be the best way to grab the url from a line of html then?
@shane A more maintainable way would be to use an HTML parser class. For example the PHP Simple HTML DOM Parser
@drrcknlsn: in this case it will work. could you tell me situation when would not regex work on this?
@genesis It will not match <img src=foo/> and other cases. It will also match things that it should not, like <img src=''''''''''''>. @shane You should use a DOM parser.
|
2

I think it would be better if used DOMDocument object:

$text = '<html><body><p>ala bala</p><img src="/images/mylondon.jpg" /></body></html>';
$htmlDom = new DOMDocument;
$htmlDom->loadHTML($text);

$imageTags = $htmlDom->getElementsByTagName('img');

$extractedImages = array();
foreach($imageTags as $imageTag){
   $extractedImages[] = $imageTag->getAttribute('src');
}

echo '<pre>'; var_dump($extractedImages); exit;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.