Removing emojis from variable

China☆狼群 提交于 2019-12-04 08:44:00

问题


I'm using Smarty to pass in and display the contents of a first_name variable. Some users have Emoji characters (http://en.wikipedia.org/wiki/Emoji) in their first_name and I am wondering how I can either a) conditionally not display a user's first_name if it contains emojis or b) filter out emoji characters from first_name. Can this be done with Smarty? Can it be done with PHP in Smarty?


回答1:


The emoji are encoded in the block U+1F300–U+1F5FF.

preg_replace('/\xEE[\x80-\xBF][\x80-\xBF]|\xEF[\x81-\x83][\x80-\xBF]/', '', $first_name)

this will strip those out




回答2:


I tried some of the solutions posted above, but no one worked, however, when I converted the string to UTF-8 using the mb_ function it works properly.

You can use:

trim( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', 
      mb_convert_encoding( $emojiString, "UTF-8" ) ) );

Works for me.




回答3:


Q: Can this be done with Smarty? A: Yes.

Q: Can it be done with PHP in Smarty? A: Yes. But please don't use PHP tags on template side.

Try to use a variable modifier on a template variable instead.

{* apply modifier to a variable *}
{$first_name|emojistrip}

Put the following content into a file named "modifier.emojistrip.php" in the folder "/smarty/plugins/".

function smarty_modifier_emojistrip($string)
{       
    return preg_replace('/\xEE[\x80-\xBF][\x80-\xBF]|\xEF[\x81-\x83][\x80-\xBF]/', '', $string);
}



来源:https://stackoverflow.com/questions/13148690/removing-emojis-from-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!