I was just working with something similar, and I came up with this little piece of code, it also contemplates the use of latin characters.
This is the sample string:
$str = 'El veloz murciélago hindú comía fe<!>&@#$%&!"#%&?¡?*liz cardillo y kiwi. La cigüeña ¨^;.-|°¬tocaba el saxofón detrás del palenque de paja';
First I convert the string to htmlentities just to make it easier to use later.
$friendlyURL = htmlentities($str, ENT_COMPAT, "UTF-8", true);
Then I replace latin characters with their corresponding ascii characters (á
becomes a
, Ü
becomes U
, and so on):
$friendlyURL = preg_replace('/&([a-z]{1,2})(?:acute|lig|grave|ring|tilde|uml|cedil|caron);/i','\1',$friendlyURL);
Then I convert the string back from html entities to symbols, again for easier use later.
$friendlyURL = html_entity_decode($friendlyURL,ENT_COMPAT, "UTF-8");
Next I replace all non alphanumeric characters into hyphens.
$friendlyURL = preg_replace('/[^a-z0-9-]+/i', '-', $friendlyURL);
I remove extra hyphens inside the string:
$friendlyURL = preg_replace('/-+/', '-', $friendlyURL);
I remove leading and trailing hyphens:
$friendlyURL = trim($friendlyURL, '-');
And finally convert all into lowercase:
$friendlyURL = strtolower($friendlyURL);
All together:
function friendlyUrl ($str = '') {
$friendlyURL = htmlentities($str, ENT_COMPAT, "UTF-8", true);
$friendlyURL = preg_replace('/&([a-z]{1,2})(?:acute|lig|grave|ring|tilde|uml|cedil|caron);/i','\1',$friendlyURL);
$friendlyURL = html_entity_decode($friendlyURL,ENT_COMPAT, "UTF-8");
$friendlyURL = preg_replace('/[^a-z0-9-]+/i', '-', $friendlyURL);
$friendlyURL = preg_replace('/-+/', '-', $friendlyURL);
$friendlyURL = trim($friendlyURL, '-');
$friendlyURL = strtolower($friendlyURL);
return $friendlyURL;
}
Test:
$str = 'El veloz murciélago hindú comía fe<!>&@#$%&!"#%&-?¡?*-liz cardillo y kiwi. La cigüeña ¨^`;.-|°¬tocaba el saxofón detrás del palenque de paja';
echo friendlyUrl($str);
Outcome:
el-veloz-murcielago-hindu-comia-fe-liz-cardillo-y-kiwi-la-ciguena-tocaba-el-saxofon-detras-del-palenque-de-paja
I guess Gumbo's answer fits your problem better, and it's a shorter code, but I thought it would be useful for others.
Cheers,
Adriana