phpregexpreg-replaceslugurl-parsing

Replace the trailing digits of a URI with corresponding slug text


Here is the existing preg_match() code:

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

It 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 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?


Solution

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

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