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-‘)
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.
$url = strtolower($inputString);
$patterns = $replacements = array();
$patterns = '/(&|&)/i';
$replacements = '-and-';
$patterns = '/[^a-zA-Z01-9]/i';
$replacements = '-';
$patterns = '/(-+)/i';
$replacements = '-';
$patterns = '/(-$|^-)/i';
$replacements = '';
$url = preg_replace($patterns, $replacements, $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?
- This happened since May, 2010. In case that you may consider something similar.
- Install Lubuntu 15.10 on Asus x205ta-BING-FD0039BS
- Create human friendly URL using preg_replace and regular expression in PHP
- How does Google search ranking work?
- Our feet’re touching the same ground
- Flutter get group duplicate issue
- Change the default main domain folder to subfolder
- 37 helpful features of Firefox web developer plug-in
- The list of 7 web browsers that involve web developer’s life
- SQ3R Reading Method
- View all articles »