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?

1
  • have you heard about explode function? $var1 = explode('/',$var); and then echo $var1[0] $var1[1] $var1[2] $var1[3]; to show the contents Commented Jan 31, 2011 at 16:36

3 Answers 3

4
[^\/]+?\.png

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

$_? Smells like you are coming from the PERL area ;)
@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
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.
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.

3 Comments

Brad's answer is definitely the way to go, then.
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.
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.
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']);

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.