PHP: Url rewrite using regular expression.

There is a terms called grouping at Perl regular expression. That means $1, $2, $3 which are the matching groups from last performed regular expression matching. This grouping you can use from your PHP regex too.

For example you have a URL like http://www.xyz.com/12345 and you want to convert it into another format, and the format is http://www.xyz.com?p=12345. Using Regex and grouping variables you can easily transform the format of URL into your desired one.

Here is the small code. Inside the code, I just took the digits inside (..) as a group of function preg_replace(). And inside second parameter of preg_replace() function, I just added the id into the different formatted URL.
$url = "http://www.xyz.com/12345";
$url = preg_replace('/.*?\/(\d+)/', "http://www.xyz.com?p=$1", $url);
print $url . "\n";

You can use more complex regular expression too while using grouping. There are other ways to do this. But using regex this is a very simple task.

Comments