Chanon raise his hand

Work like you don't need the money
Love like you'll never be hurt
Sing like nobody's listening
Dance like nobody's watching
More about me »

Create human friendly URL using preg_replace and regular expression in PHP

This post explain how can you generate human readable URL (friendly URL for SEO) from the given string. Using regular expression and preg_replace in PHP.

Concept

The concept below are applied to the given string in order to create the friendly URL using PHP script.

  • URL must be lower case
  • ‘&’ or ‘&’ (html special character to display ‘&’) must be converted to ‘-and-‘
  • Any characters except English letters or numbers must be converted to ‘-‘
  • en dash (-) is not allowed to be repeated (E.g. no ‘—-‘)
  • en dash is not allowed at the start or ending of URL phase (e.g. no ‘-friendly-url-‘)

For example the string ‘convert “php.net” title into human readable url‘ will be converted to ‘convert-php-net-title-into-human-readable-url‘ Coding

Coding

The code below show PHP function that return human readable URL from the given string. The further section explain the work flow of this code.

1
function friendlyURL($inputString){
2
$url = strtolower($inputString);
3
$patterns = $replacements = array();
4
$patterns[0] = '/(&|&)/i';
5
$replacements[0] = '-and-';
6
$patterns[1] = '/[^a-zA-Z01-9]/i';
7
$replacements[1] = '-';
8
$patterns[2] = '/(-+)/i';
9
$replacements[2] = '-';
10
$patterns[3] = '/(-$|^-)/i';
11
$replacements[3] = '';
12
$url = preg_replace($patterns, $replacements, $url);
13
return $url;
14
}

How it works?

  • line 2 – lower case the input using PHP build-in function strtolower
  • line 3 – declare $patterns and $replacement as Array
  • line 4,5 – match ‘& or &’ and replace with ‘-and-‘
  • line 6,7 – match non Alphabets or number and replace with ‘-‘
  • line 8,9 – match the single or repeated en dash (—-) and replace with single en dash (-)
  • line 10,11 – match en dash at the beginning of phase ($-) or en dash the end of phase (^-) and delete

That’s all it is, please use the comment below if you have any questions.