PHP 将特殊字符输出为十六进制
PHP output specialchars as hex
有没有办法将特殊字符(例如&符号 &
输出为 &
而不是 &
使用 htmlenties 或 htmlspecialchars 时,我找不到提供此行为的设置。
任何建议。
你需要 urlencode
然后 str_replace
才能做到这一点
$string = 'Whosebug # & " ';
$string = urlencode($string);
$find = ['%', '+'];
$replace = ['&#x', ' '];
$string = str_replace($find,$replace, $string);
echo $string;
我自己想出来了。
我使用 mb_ord 与 ord 类似,除了它用于像 UTF-8 这样的多字节编码。
此外,它仅在安装了 PHP 7.2 后才有效。
<?php
$text = html_entity_decode('∞ä€äãâ',ENT_COMPAT | ENT_HTML401,'UTF-8');
$text_converted = '';
for($i=0;$i<mb_strlen($text,'UTF-8');$i++){
$text_converted .= sprintf('&#x%X;',mb_ord(mb_substr($text,$i,1,'UTF-8')));
}
echo $text_converted;
echo '<br>';
echo str_replace('&','&',$text_converted);
echo '<br>';
echo $text;
?>
有没有办法将特殊字符(例如&符号 &
输出为 &
而不是 &
使用 htmlenties 或 htmlspecialchars 时,我找不到提供此行为的设置。
任何建议。
你需要 urlencode
然后 str_replace
才能做到这一点
$string = 'Whosebug # & " ';
$string = urlencode($string);
$find = ['%', '+'];
$replace = ['&#x', ' '];
$string = str_replace($find,$replace, $string);
echo $string;
我自己想出来了。 我使用 mb_ord 与 ord 类似,除了它用于像 UTF-8 这样的多字节编码。 此外,它仅在安装了 PHP 7.2 后才有效。
<?php
$text = html_entity_decode('∞ä€äãâ',ENT_COMPAT | ENT_HTML401,'UTF-8');
$text_converted = '';
for($i=0;$i<mb_strlen($text,'UTF-8');$i++){
$text_converted .= sprintf('&#x%X;',mb_ord(mb_substr($text,$i,1,'UTF-8')));
}
echo $text_converted;
echo '<br>';
echo str_replace('&','&',$text_converted);
echo '<br>';
echo $text;
?>