不适用于表情符号的htmlentites [英] htmlentites not working for emoji
本文介绍了不适用于表情符号的htmlentites的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试显示字符html实体
echo htmlentities(htmlentities("&"));
//outputs &
echo htmlentities(htmlentities("<"));
//outputs <
但它似乎不适用于表情符号
echo htmlentities(htmlentities("😎"));
//outputs 😎
如何使其输出😎
?
编辑:
我正在尝试显示用户输入的字符串,并对所有html实体进行编码。
echo htmlentities(htmlentities($input))
示例:
"this & that 😎" -> "this & that 😎"
推荐答案
这适用于常规的Htf实体、Utf-8表情符号(和其他utf内容),当然也适用于常规字符串。
我只是在处理空字符串值时遇到了问题,所以我必须将此条件放入函数中。
function entities( $string ) {
$stringBuilder = "";
$offset = 0;
if ( empty( $string ) ) {
return "";
}
while ( $offset >= 0 ) {
$decValue = ordutf8( $string, $offset );
$char = unichr($decValue);
$htmlEntited = htmlentities( $char );
if( $char != $htmlEntited ){
$stringBuilder .= $htmlEntited;
} elseif( $decValue >= 128 ){
$stringBuilder .= "&#" . $decValue . ";";
} else {
$stringBuilder .= $char;
}
}
return $stringBuilder;
}
// source - http://php.net/manual/en/function.ord.php#109812
function ordutf8($string, &$offset) {
$code = ord(substr($string, $offset,1));
if ($code >= 128) { //otherwise 0xxxxxxx
if ($code < 224) $bytesnumber = 2; //110xxxxx
else if ($code < 240) $bytesnumber = 3; //1110xxxx
else if ($code < 248) $bytesnumber = 4; //11110xxx
$codetemp = $code - 192 - ($bytesnumber > 2 ? 32 : 0) - ($bytesnumber > 3 ? 16 : 0);
for ($i = 2; $i <= $bytesnumber; $i++) {
$offset ++;
$code2 = ord(substr($string, $offset, 1)) - 128; //10xxxxxx
$codetemp = $codetemp*64 + $code2;
}
$code = $codetemp;
}
$offset += 1;
if ($offset >= strlen($string)) $offset = -1;
return $code;
}
// source - http://php.net/manual/en/function.chr.php#88611
function unichr($u) {
return mb_convert_encoding('&#' . intval($u) . ';', 'UTF-8', 'HTML-ENTITIES');
}
/* ---- */
var_dump( entities( "&" ) ) . "
";
var_dump( entities( "<" ) ) . "
";
var_dump( entities( "😎" ) ) . "
";
var_dump( entities( "☚" ) ) . "
";
var_dump( entities( "" ) ) . "
";
var_dump( entities( "A" ) ) . "
";
var_dump( entities( "Hello 😎 world" ) ) . "
";
var_dump( entities( "this & that 😎" ) ) . "
";
这篇关于不适用于表情符号的htmlentites的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文