2

i want to give regex a pattern and force it to read it all ..

http://example.com/w/2/1/x/some-12345_x.png

i want to target "some-12345_x"
i used this /\/(.*).png/, it doesnt work for some reason

how do i force it to remember it must start with / and end with .png?

1
  • Is regexing for /some-12345_x.png and then substringing to some-12345_xan option? Commented Oct 9, 2012 at 14:12

4 Answers 4

1

If you always want to get the final file-name, minus the extension, you could use PHP's substr() instead of trying to come up with a regex:

$lastSlash = strrpos($url, '/') + 1;
$name = substr($url, $lastSlash, strrpos($url, '.') - $lastSlash);

Also, a more readable method would be to use PHP's basename():

$filename = basename($url);
$name = substr($filename, 0, strpos($filename, '.'));

To actually use a regex, you could use the following pattern:

.*/([^.]+).png$

To use this with PHP's preg_match():

preg_match('|.*/([^.]+).png$|', $url, $matches);
$name = $matches[1];
Sign up to request clarification or add additional context in comments.

Comments

1

You can do:

^.*/(.*)\.png$

which captures what occurres after the last / till .png at the end.

Comments

1

You might need to use reg-ex in this situation for a particular reason, but here's an alternative where you don't:

$url = "http://example.com/w/2/1/x/some-12345_x.png";
$value = pathinfo($url);
echo $value['filename'];

output:

some-12345_x

pathinfo() from the manual

Comments

1

How about:

~([^/]+)\.png$~

this will match anything but / until .png at the end of the string.

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.