Friday, September 5, 2008

PHP: Url rewrite using regular expression.

Share at Facebook

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 and you want to convert it into another format, and the format is 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 = "";
$url = preg_replace('/.*?\/(\d+)/', "$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.

No comments: