Question

Currently on my site I have duplicate URLs as follows:

example.com/post_title/
example.com/post_title_2/
example.com/post_title_33/

I have a canonical url set up in my site's header file that's used on every page as so:

<link rel="canonical" href="<?php echo $url ?>" />

where $url is the page url. So for example if the page URL is example.com/post_title_33/, the canonical is example.com/post_title_33/

My question is what would be the best way to make it so the canonical URL is always example.com/post_title/?

The numbers at the end of the URL can be any number not just 2 or 33 like I used in my example.

Was it helpful?

Solution

You could remove the numbers and leading underscore with preg_replace:

<?

$input = array(
  'example.com/post_title/',
  'example.com/post_title_2/',
  'example.com/post_title_33/'
);

print_r(preg_replace('/_[0-9]+/', '', $input));

?>

Demo: https://eval.in/63138

Manual: http://us3.php.net/preg_replace

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top