Uses of the SEO friendly URL helps to improve the search engine ranking. Also, the search engine friendly URL gives an idea about the web page content. The different between normal URL and SEO friendly URL is given below.
- Noraml URL: http://www.example.com/posts.php?id=123
- SEO URL: http://www.example.com/php-tutorial-for-beginners
In this tutorial, we’ll show you how to generate SEO friendly URL from string using PHP. Our example script makes it easy to convert title string to SEO friendly URL in PHP. We’ve grouped together all the PHP code into a function named
generateSeoURL(). The generateSeoURL() function automatically create clean and SEO friendly URL slug from string.PHP function to create SEO Friendly URL
generateSeoURL() function takes a “title” string as input and creates a human-friendly URL string with a “-” string 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).
<?php
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(
'&.+?;' => '',
'[^\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);
return trim(trim($string, $separator));
}
Uses
Provide the article title or string in the first parameter ofgenerateSeoURL() function. If you want to restrict words on URL, provide the number of the words otherwise can omit it.Without Words Limit:
With Words Limit:
<?php
$postTitle = 'Adding Google Map on Your Website within 5 Minutes';
$seoFriendlyURL = generateSeoURL($postTitle);
//Output will be: adding-google-map-on-your-website-within-5-minutes
<?php
$postTitle = 'Adding Google Map on Your Website within 5 Minutes';
$seoFriendlyURL = generateSeoURL($postTitle, 6);
//Output will be: adding-google-map-on-your-website
Comments