42
function seoUrl($string)
{
$string = trim($string); // Trim String
$string = strtolower($string); //Unwanted: {UPPERCASE} ; / ? : @ & = + $ , . ! ~ * ' ( )
$string = preg_replace("/[^a-z0-9_\s-]/", "", $string); //Strip any unwanted characters
$string = preg_replace("/[\s-]+/", " ", $string); // Clean multiple dashes or whitespaces
$string = trim($string);
$string = preg_replace("/[\s_]/", "-", $string); //Convert whitespaces and underscore to dash
return $string;
}
Explanation of the Function:
strtolower(): Converts the entire string to lowercase to ensure consistency.
str_replace(): Replaces spaces with hyphens (-).
preg_replace() with '/[^a-z0-9-]/': Uses a regular expression to remove any characters that are not lowercase letters, digits, or hyphens.
preg_replace() with '/-+/': Ensures that multiple hyphens are replaced with a single hyphen.
trim(): Removes any leading or trailing hyphens.