views:

127

answers:

3

Hi there I need a bit of help.

Here is the existing preg_match code:

preg_match("/(\/)([0-9]+)(\/?)$/", $_SERVER["REQUEST_URI"], $m);

which does a good job of detecting the post_id in the following URI string:

http://www.example.com/health-and-fitness-tips/999/

I believe that should be enough background.

I'm changing the 999, the post_id, to how-do-I-lose-10kg-in-12-weeks', the post_title`, and need to change the pre_match regex to detect the new string.

My first thought was to just add [a-z]- to the end of the regex making the following regex:

"/(\/)([0-9][a-z]/-+)(\/?)$/"

It is possibly this simple? If not, what is wrong with the above?

A: 

I would just use \w:

preg_match('!/([-\w]+)/?$!', $_SERVER['REQUEST_URI'], $m);

From Character Classes or Character Sets:

\w stands for "word character", usually [A-Za-z0-9_]. Notice the inclusion of the underscore and digits.

cletus
what is `\w`? Would you mind expanding a tiny bit?
ivannovak
+2  A: 

Not quite: ([0-9][a-z]/-+) is "a number, followed by a letter, followed by at least one dash."

You want ([-0-9a-z]+).

Tordek
A: 

\w stands for word, can be letter both upper case and lower case A to Z and a to z, number 0 to 9 or _. It's equivalent to [A-Za-z0-9_]. You can test in the online tester here.

unigg