Last Updated: February 25, 2016
·
1.498K
· pedrohcan

Normalizing strings with preg_replace

Well, some time ago I had to normalize a string so that it could be used in a friendly url.
I used preg_replace wich uses regexp and is way simpler in this case. Ofcourse, my solution is based on what I needed in that moment, so you may need some changes if you want to use it. Still it's worth sharing and to take a look.

function normalizeString($name){
// Lowercase it all
$name = strtolower($name);

// Just normal vogals must remain
$name = preg_replace('/[aáàãâäAÁÀÃÂÄ]/', 'a', $name);
$name = preg_replace('/[eéèêëEÉÈÊË]/', 'e', $name);
$name = preg_replace('/[iíìîïIÍÌÎÏ]/', 'i', $name);
$name = preg_replace('/[oóòõôöOÓÒÕÔÖ]/', 'o', $name);
$name = preg_replace('/[uúùûüUÙÚÛÜ]/', 'u', $name);
$name = preg_replace('/[cçCÇ]/', 'c', $name);

// No more than 1 space sequentially
$name = preg_replace('/\s{2,}/', ' ', $name);

// Spaces must became underscores
$name = preg_replace('/ /', '_', $name);

// Just letters and numbers
$name = preg_replace('/[^a-z0-9_]/', '', $name);

return $name;

}