gpt4 book ai didi

php - htmlentities 不适用于表情符号

转载 作者:可可西里 更新时间:2023-11-01 12:48:19 27 4
gpt4 key购买 nike

我正在尝试显示字符 html 实体

echo htmlentities(htmlentities("&"));
//outputs &
echo htmlentities(htmlentities("<"));
//outputs &lt;

但它似乎不适用于表情符号

echo htmlentities(htmlentities("😎"));
//outputs 😎

如何让它输出😎


编辑:

我正在尝试显示用户输入的所有 html 实体都已编码的字符串。
echo htmlentities(htmlentities($input))

例子:"this & that 😎"-> "this & that 😎"

最佳答案

这适用于常规 HTML 实体、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( "&" ) ) . "\n";
var_dump( entities( "<" ) ) . "\n";
var_dump( entities( "😎" ) ) . "\n";
var_dump( entities( "☚" ) ) . "\n";
var_dump( entities( "" ) ) . "\n";
var_dump( entities( "A" ) ) . "\n";
var_dump( entities( "Hello 😎 world" ) ) . "\n";
var_dump( entities( "this & that 😎" ) ) . "\n";

关于php - htmlentities 不适用于表情符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34956163/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com