0

"Consider this as example and extract the image name from this string"(this part is also included as a question".

<img src='http://www.example.com/Imagename.jpg' height='400px' width='600px'>

-------> work on the material provided above along with the sentence ... i hav combination of string and tag ... and i want to extract only the filename from all these stuff .

How to do this ?

user3134101
  • 49
  • 1
  • 10

2 Answers2

0

You can use a simple regex to get it from the string, or use SimpleXMLElement

Example

<?php

$input = "<img src='http://www.example.com/Imagename.jpg' height='400px' width='600px' />";

$element= new SimpleXMLElement($input);
var_dump(basename((string) $element->attributes()->src));

Will output the desired result: string 'Imagename.jpg' (length=13)

Example using regular expression (i recommend use DOM or SimpleXMLElement like i've posted), but, if you want a simpler way like using a simple regex, you can do that:

<?php

preg_match("/src='(?P<url>([^']*?))'/", $input, $matches);
$filename = isset($matches['url']) ? basename($matches['url']) : null;

var_dump($filename);

It will produce the same output.

And a full example if you want scrap all HTML, you can do that:

<?php

$html = <<<HTML
<!DOCTYPE HTML>
<html lang="en-US">
<head>
  <meta charset="UTF-8">
</head>
<body>
lalala 
<img src='http://www.example.com/Imagename.jpg' height='400px' width='600px' />
</body>
</html>
HTML;

function withEachImage ($html, callable $callback) {
   libxml_use_internal_errors(true);

  $document = new DOMDocument();
  $document->loadHTML($html);

  foreach ($document->getElementsByTagName('img') as $img) {
    call_user_func_array($callback, array($img->getAttribute('src')));
  }
}

withEachImage($html, function ($src) {
  echo basename($src);
});
Andrey
  • 1,476
  • 1
  • 11
  • 17
0

There are a number of ways to go about doing this, assuming that the image filename could change, or you may alternate between " and ', this is how i would do it;

function getFileName($myImage){
$myArray = explode(" ",$myImage);
$subArray = explode("/",$myArray[1]);
return substr($subArray[count($subArray)-1],0,-1);
}


$source = "<img src='http://www.example.com/Imagename.jpg' height='400px' width='600px'>";
$myImg = getFileName($source);

print $myImg;

Code has been tested and works

Output: Imagename.jpg

you could even make it check for 'src' so it doesnt matter what order the parameters are in:

function getFileName($myImage){
$myArray = explode(" ",$myImage);
$useKey = 0;
foreach($myArray as $key => $value){
  if(substr($value,0,3)=="src"){
    $useKey = $key;
  }
}
$subArray = explode("/",$myArray[$useKey]);
return substr($subArray[count($subArray)-1],0,-1);
}


$source = "<img height='400px' src='http://www.example.com/Imagename.jpg' width='600px'>";
$myImg = getFileName($source);

print $myImg;