How to replace UTF-8 characters with similar-looking ASCII characters with PHP?
Asked Answered
W

1

7

I have a problem about Unicode. I need a function in PHP to convert the string:

Xin chào tất cả các bạn. Mình không biết tiếng anh.

To:

Xin chao tat ca cac ban. Minh khong biet tieng anh.

Can anybody help me?

Wildawildcat answered 20/4, 2014 at 2:4 Comment(2)
RelatedAccursed
The title doesn't match with the question, the text encoding is the same in the 2 strings (Stack Overflow uses UTF-8). Your question is more about transforming the text by removing the non-ASCII characters.Slambang
C
9

Use iconv with the //TRANSLIT modifier:

$str1 = "Xin chào tất cả các bạn. Mình không biết tiếng anh.";
$str2 = iconv("UTF-8", "ASCII//TRANSLIT", $str1);
print($str1.PHP_EOL.$str2);

The output will be:

Xin chào tất cả các bạn. Mình không biết tiếng anh.
Xin chao tat ca cac ban. Minh khong biet tieng anh.

DEMO

Cheyney answered 20/4, 2014 at 2:53 Comment(3)
Thanks. But Code not support all version PHP5 and error on XAMP with version PHP5.5 "Notice: iconv(): Detected an illegal character in input string in". Please help and check on phpversion higher. Demo: linkWildawildcat
That error has nothing to do with the PHP version. It has been caused by the locale of the server. Use setlocale(LC_ALL, "en_GB.UTF-8"); to get rid of your problem. DEMOCheyney
Thanks very much! Code error with PHP5.5.9 :( linkWildawildcat

© 2022 - 2024 — McMap. All rights reserved.