Search code examples
javascriptphpunicode

How to convert unicode to ascii in JavaScript or PHP?


I have an app that one of my users uses some kind of custom keyboard that changes the fonts they typed.

They entered these characters to the app searchbox.

𝙈𝙖𝙢𝙮𝙥𝙤𝙠𝙤

I believe this is unicode characters? Correct me If I'm wrong.

The word then gets converted to query params.

?search=%F0%9D%99%88%F0%9D%99%96%F0%9D%99%A2%F0%9D%99%AE%F0%9D%99%A5%F0%9D%99%A4%F0%9D%99%A0%F0%9D%99%A4

and the server returns no result.

How to change the characters back to regular ascii "Mamypoko" so that my apps show desired result, regardless of user's keyboard?

I don't mind using JavaScript or PHP, I just need to convert before calling MySQL query.


Solution

  • For this particular case, iconv with the //TRANSLIT flag could help you. See https://www.php.net/manual/en/function.iconv.php

    $search="%F0%9D%99%88%F0%9D%99%96%F0%9D%99%A2%F0%9D%99%AE%F0%9D%99%A5%F0%9D%99%A4%F0%9D%99%A0%F0%9D%99%A4";
    
    $converted = iconv("UTF-8", "ISO-8859-1//TRANSLIT", urldecode($search));
    
    var_dump($converted);
    

    This gives you:

    string(8) "Mamypoko"