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.


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 “” title into human readable url‘ will be converted to ‘convert-php-net-title-into-human-readable-url


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.

function friendlyURL($inputString){
	$url = strtolower($inputString);
	$patterns = $replacements = array();
	$patterns[0] = '/(&|&)/i';
	$replacements[0] = '-and-';
	$patterns[1] = '/[^a-zA-Z01-9]/i';
	$replacements[1] = '-';
	$patterns[2] = '/(-+)/i';
	$replacements[2] = '-';
	$patterns[3] = '/(-$|^-)/i';
	$replacements[3] = '';
	$url = preg_replace($patterns, $replacements, $url);
	return $url;

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.

  • I donate $100/mo, why?

  • My Photography

  • Above the crowd Cage Side forward Walk away Endless rain Vivid Sydney Before Dawn