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

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.

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.

  • TimNguyenBSM

    Been looking for a script like this online, and must say yours is the simplest I’ve found. No over engineering here! =) Thank you so much.

  • I donate $100/mo, why?

  • My Photography

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