简体   繁体   中英

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.

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"

You can get a exact result when you use urldecode() function in php.

code:

$myString= 'https://lamesarv.com?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
';

echo urldecode($myString);

result:

https://lamesarv.com?search=𝙈𝙖𝙢𝙮𝙥𝙤𝙠𝙤

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM