Friday 17 June 2016

How to Create SEO friendly URLs in PHP

This is a handy PHP code snippet which accepts a regular string as input and returns a SEO friendly slug which can become a part of a URL.
public function stringToSlug($string){
  //Remove white spaces from both sides of a string
  $string = trim(string);
  
  //Lower case everything
  $string = strtolower($string);
  
 //Make alphanumeric (removes all other characters)
 $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
  
 //Clean up multiple dashes or whitespaces
 $string = preg_replace("/[\s-]+/", " ", $string);
  
 //Convert whitespaces and underscore to dash
 $string = preg_replace("/[\s_]/", "-", $string);
  
 return $string;
}

0 comments:

Post a Comment