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.

Useful Read : Export Data From MySQL table to CSV File using PHP

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

Leave a Comment.