Home    Articles

 

How to generate links in php using preg_replace

 

In order to generate a link for a custom page using the page title you need to remove all unwanted caracters.
The best way to do this is to use “white list” sistem.

In this way you will replace all character with a given caracter. All characters that comply with the white list pattern will remain in the url.

An example of doing this:

<?php
$link = '#This is% my ^page title@';
$url = preg_replace('/[^a-zA-Z0-9]+/', '-', $link);
$url = trim($url,'-');
$url = strtolower($url);
echo $url;
//result will be: " this-is-my-page-title "
?>

That’s all.

by