Create SEO Friendly URL in PHP
Super Admin 12-05-2023 353 Tutorial
The generateSeoURL()
function automatically creates SEO friendly URL slug from the string using PHP. A title string needs to be passed as input and it returns a human-friendly URL string with a hyphen (-
) as the word separator.
$string
– Required. The string which you want to convert to the SEO friendly URL.$wordLimit
– Optional. Restrict words limit on SEO URL, default is 0 (no limit).
function generateSeoURL($string, $wordLimit = 0){
$separator = '-';
if($wordLimit != 0){
$wordArr = explode(' ', $string);
$string = implode(' ', array_slice($wordArr, 0, $wordLimit));
}
$quoteSeparator = preg_quote($separator, '#');
$trans = array(
'&.+?;' => '',
'[^wd _-]' => '',
's+' => $separator,
'('.$quoteSeparator.')+'=> $separator
);
$string = strip_tags($string);
foreach ($trans as $key => $val){
$string = preg_replace('#'.$key.'#iu', $val, $string);
}
$string = strtolower($string);
return trim(trim($string, $separator));
}