Search code examples
phppermalinks

How to create permalinks without multiple dashes behind each other?


I am trying to create a function to create permalinks. This is what I have until now:

public function createPermalink($permalink)    
{    
  $new_perma = strtolower($permalink);    
  $searchsigns = array('Ö', 'Ä', 'Ü', 'ß', '-', '_', ' ', 'ö', 'ä', 'ü');    
  $replaces = array('oe', 'ae', 'ue', 'ss', '', '-', '-', 'oe', 'ae', 'ue');    
  $new_perma = str_replace($searchsigns, $replaces, $new_perma);    
  $new_perma = preg_replace('/[^a-z0-9_-]/isU', '', $new_perma);    
  return $new_perma;    
}

Now imagine the variable $permalink would be say 5 free spaces (doesn't make sense, but a user could possibly enter it). Now what would happen is that the $new_perma would be ----- So there is the problem, in the URL there is only one - allowed. Obviously I could at the end use str_replace to replace 2, 3, 4, 5 ... dashes behind each other. But I would need to specify the search pattern for any possible amount of dashes. So what I need is a way to remove all dashes inside the variable $new_parma, which are more than one in a row.


Solution

  • Add this just before the return of your function:

    $new_perma = preg_replace('/-+/', '-', $new_perma);
    

    The + means 'one or more'. So this pattern replaces one or more dashes with a single dash.