Clean URL Slug From Ugly String Using PHP

Google strongly guide webmasters to make there website URLs SEO friendly or Google friendly. Creating URL from title is the best way to make URLs more user or search engine friendly. This simple function can make clean and friendly URL slug from ugly to uglier title or string.


The URL Slug Function:
/**
 * URL Slug
 * @param str $str
 * @return str
 */
function url_slug($str)
{	
	#convert case to lower
	$str = strtolower($str);
	#remove special characters
	$str = preg_replace('/[^a-zA-Z0-9]/i',' ', $str);
	#remove white space characters from both side
	$str = trim($str);
	#remove double or more space repeats between words chunk
	$str = preg_replace('/\s+/', ' ', $str);
	#fill spaces with hyphens
	$str = preg_replace('/\s+/', '-', $str);
	return $str;
}

Usage:
$title = '  This -iS- (my)   @$ugly@#          tiTle !!!!!!!!!!!!!!!!!!!! ';
echo url_slug($title);

Output:
this-is-my-ugly-title

No comments:

Post a Comment

Go to top