tags:

views:

73

answers:

3

Hello!

Please help!

I'm on PHP. I have an url: 'http://example.com/articles/123a/view', how do I get '123a' only from this string with regular expression (preg_replace, probably). Can't figure it out. Thanks in advance.

A: 

Try this regular expression:

^(?:[^/]*/){4}([^/]+)

preg_match('/^(?:[^\\/]*\\/){4}([^\\/]+)/', $str, $match)

$match[1] will then hold your 123a.

Gumbo
Doesn't work, it returns 'Unknown modifier '/' ' error
Andersson83
I typed this: preg_replace('^(?:[^/]*/){4}([^/]+)', '', http://example.com/articles/123a/view)
Andersson83
@Andersson83: You forgot the delimiters.
Gumbo
+7  A: 

Why Regex?

$parts = explode('/', 'http://example.com/articles/123a/view');
echo $parts[4];
Philippe Gerber
The third parameter of `explode` allows you to set a limit. You could set it to `6` to prevent some possible superfluous exploding.
Geert
A: 

Dumb me! Why did I forget about explode? Thank you everyone!

Andersson83
Since the proper answer was provided you should accept it (to the left of the answer). Also this should really be a comment not an answer.
EBGreen