15

I am trying to convert characters like:

ë, ä, ï, ö, etc.

To normal characters like:

e, a, i, o, etc.

What is the best way to do this? I've tried many things, like preg_replace and str_replace.

Can someone help me out?

-- EDIT --

What I tried, was:

$ts = array("[À-Å]","Æ","Ç","[È-Ë]","/[Ì-Ï]/","/Ð/","/Ñ/","/[Ò-ÖØ]/","/×/","/[Ù-Ü]/","/[Ý-ß]/","/[à-å]/","/æ/","/ç/","/[è-ë]/","/[ì-ï]/","/ð/","/ñ/","/[ò-öø]/","/÷/","/[ù-ü]/","/[ý-ÿ]/");

$tn = array("A","AE","C","E","I","D","N","O","X","U","Y","a","ae","c","e","i","d","n","o","x","u","y");

$title = preg_replace($ts, $tn, $text);
Mossawi
  • 871
  • 2
  • 10
  • 17
  • 1
    possible duplicate of [PHP Transliteration](http://stackoverflow.com/questions/1284535/php-transliteration) – Quentin Mar 15 '12 at 13:31
  • The correct term here would be accented characters. Special characters are things like $#@/\ etc. – lgaud Mar 15 '12 at 13:53

3 Answers3

40

try this .. works for me.

iconv('utf-8', 'ascii//TRANSLIT', $text);
mpapec
  • 50,217
  • 8
  • 67
  • 127
Stewie
  • 3,103
  • 2
  • 24
  • 22
  • 4
    utf8 and utf-8 didn't work for me. chars get replaced by a question mark, that's all. – CREEATION May 14 '14 at 14:48
  • 1
    @CREE7EN Try setting the locale first: `setlocale(LC_CTYPE, 'en_US.UTF8');` After that encoding appears to be better. – Neograph734 Sep 03 '15 at 08:19
  • I had two strings same identical words strcmp returns value greater then 0 after I used iconv solution strcmp returns 0 which is equal to each other – sdx11 Dec 19 '20 at 18:42
33

i like stewies' answer, but for completeness this works for me.

preg_replace("/&([a-z])[a-z]+;/i", "$1", htmlentities($foo));
David Chan
  • 7,347
  • 1
  • 28
  • 49
  • This would work better IMO as it does not depend on the server's locale. I had some issues where `iconv('utf-8', 'ascii//TRANSLIT', $text);` would work fine locally, but once pushed the results were different, probably because of different server locale. – FooBar Aug 11 '20 at 08:42
0

For example, it is create a simple readable URL from a content title:

function cleanurl($title) {
        return urlencode(strtolower(str_replace(" ","-",preg_replace("/&([a-z])[a-z]+;/i", "$1", htmlentities($title)))));
}