How to create SEO friendly URL using PHP

SEO friendly URL using PHP we are going to implement creating SEO friendly Slug based on title. That require in Custom PHP Blog website. So, create PHP function and pass title as $string variable. you can set word limit as per your needs.

<?php
$string="How to create SEO friendly URL using PHP";
$wordLimit=10;

$separator = '-';
    
if($wordLimit != 0){
	$wordArr = explode(' ', $string);
	$string = implode(' ', array_slice($wordArr, 0, $wordLimit));
}

$quoteSeparator = preg_quote($separator, '#');

$trans = array(
	'&.+?;'                    => '',
	'[^\w\d _-]'            => '',
	'\s+'                    => $separator,
	'('.$quoteSeparator.')+'=> $separator
);

$string = strip_tags($string);
foreach ($trans as $key => $val){
	$string = preg_replace('#'.$key.'#i'.('UTF8_ENABLED' ? 'u' : ''), $val, $string);
}

$string = strtolower($string);

echo trim(trim($string, $separator));
?>

This return output how-to-create-seo-friendly-url-using-php

Leave a Reply