I have an html string like this:

<img src="/files/vile.jpg" width="500" height="367" alt="vile.jpg" />

What is the best way to extract only the path: /files/vile.jpg from the above string? I'm not too familiar with regex, any help is greatly appreciated!

Comments

step3hand’s picture

I would strpos on src and on jpg and then return the string in between.

prakashp’s picture

You could try something like this

$string = '<img src="/files/vile.jpg" width="500" height="367" alt="vile.jpg" />';
$pattern = '/.*src="(.*)".*/U';
$matches = array();
if (preg_match($pattern, $string, $matches)) {
  echo "The image path is {$matches[1]}";
} 

hope this helps

drupalzack’s picture

Thanks prakashp!

felipensp’s picture

My suggestion:

<?php
$string = '<img src=/files/vile.jpg width="500" height="367" alt="vile.jpg" />';
if (preg_match('/src=(?:"([^"]+)"|\'([^\']+)\'|(\S+))/', $string, $matches)) {
  $path = !empty($matches[1]) ? $matches[1] : (!empty($matches[2]) ? $matches[2] : $matches[3]);
  echo "The image path is ". $path;
}
?>

Accepts: "path", 'path', path.

drupalzack’s picture

Thank you! this improvement is even better!