2

I have a string:

...<a href="http://mple.com/nCCK8.png">...

From this I am trying to strip out the

"nCCK8.png" part

I tried substr, but that requires 2 numbers and didn't work as it can be in different positions in the string. It does occur only once in the string.

The base string always has mple.com/ before the nCCK8.png part, and always "> after.

What is the easiest way to do this?

mrbellek
  • 2,300
  • 16
  • 20
David19801
  • 11,214
  • 25
  • 84
  • 127
  • have you heard about explode function? $var1 = explode('/',$var); and then echo $var1[0] $var1[1] $var1[2] $var1[3]; to show the contents – devasia2112 Jan 31 '11 at 16:36

3 Answers3

4
[^\/]+?\.png

$_ = null;
if (preg_match('/([^\/]+?\.png)/i',$data,$_)){
  echo $_[1];
}

Working Demo: http://www.ideone.com/3IkhB

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
  • `$_`? Smells like you are coming from the PERL area ;) – ThiefMaster Jan 31 '11 at 16:33
  • @ThiefMaster: I tend to use `$_` just because it's almost never going to collide with another user's variables names within the scope that they place my code. ;-) But, ya never know... ;p – Brad Christie Jan 31 '11 at 16:34
  • True, i didn't say it's bad anyway. There's no need to initialize it btw - byref passing of an undefined variable won't trigger a notice. – ThiefMaster Jan 31 '11 at 16:51
2

Wow, all these other answers are so complex.

$tmp = explode('/', $string);
//if you actually WANT the "nCCK8.png" part
return substr($tmp[count($tmp) - 1], 0, -2);

//if you actually want the rest of it
$tmp = $array_pop($tmp);
return substr(implode('/', $tmp), 0, -2);

Unless the string is longer than you posted, and includes other slashes, this should work.

rockerest
  • 10,412
  • 3
  • 37
  • 67
  • Brad's answer is definitely the way to go, then. – rockerest Jan 31 '11 at 16:43
  • Personally I would prefer to see explode, count and strpos used to solve the problem. Fairly trivial and easy to understand. If you must use regex, make sure to document the hell out of it. – Mr Griever Jan 31 '11 at 16:46
  • you know the minimum number of pieces before the image filename so start searching from there for a piece that contains ".png" (or whatever other file names you're looking for). Personally I'd go the regex route as it's more globally applicable but if the piece you want is normally going to be in the first one or two segments you check, this way could actually be faster. – Endophage Jan 31 '11 at 16:55
0

Get the href element via simplexml or DOM (see this answer) for instance then use parse-url to get the actual file, and finaly basename:

<?php

$href = 'http://mple.com/nCCK8.png';
$url_parts = parse_url($href);
echo basename($url_parts['path']);

?>
Community
  • 1
  • 1
Aif
  • 11,015
  • 1
  • 30
  • 44