Home Regular expressions for 301 redirect
Reply: 2

Regular expressions for 301 redirect

fredix11 Published in 2017-12-07 22:51:37Z

How can I redirect http://example.com/news.php?id=268&page=25 and all pages like http://example.com/news.php?id=X&page=Y to another page using regular expressions?

I tried using http://example.com/news.php?id=/d&page=/d.

Barmar Reply to 2017-12-07 23:07:35Z

Digits are matched with \d, not /d. To match at least 1 digit, you need to add the + quantifier. And to capture the numbers so you can copy them to the replacement URL, you need a capture group around it.

You also need to escape certain characters that have special meaning in regular expressions: . and ?.

Erik Reppen
Erik Reppen Reply to 2017-12-07 23:29:01Z
$string = 'http://example.com/news.php?id=268&page=25';
$pattern = '/^[^\?]+\?id=(\d+)&page=(\d+)$/';
$replacement = 'https://mynewdomain/with/too/many/subpaths/page.php?id=$1&page=$2';
echo preg_replace($pattern, $replacement, $string);
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.327514 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO