Ivan Novak
Ivan Novak

Reputation: 666

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?

Upvotes: 0

Views: 582

Answers (3)

unigg
unigg

Reputation: 464

\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.

Upvotes: 0

Tordek
Tordek

Reputation: 10872

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

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

Upvotes: 2

cletus
cletus

Reputation: 625037

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.

Upvotes: 0

Related Questions