function in PHP that converts a string into a SEO-friendly URL

processes it to remove spaces and special characters, and formats it to be SEO-friendly by converting it to lowercase and replacing spaces with hyphens

42

Arun Kr.
10-Jul-24
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.

@Since 2024 Arun'Log Powered by Arun Git