我只需要从用户提交的段落中获取 30 个字符。如果第 30 个字符是表情符号,则输出会显示问号。如何避免破坏表情符号?
echo substr("Hello world Hello world Hell", 0, 30);
输出:Hello world Hello world Hell??
另外,当使用 json_encode 返回输出时,输出为空。
$myvariable = array();
$myvariable['hello'] = substr("Hello world Hello world Hell ", 0, 30);
echo json_encode($myvariable);
Run Code Online (Sandbox Code Playgroud)
我认为最简单的解决方案是使用 mb_substr
根据字符数执行多字节安全 substr() 操作。
php > $myvariable = array();
php > $myvariable['hello'] = mb_substr("Hello world Hello world Hell ", 0, 30);
php > var_dump($myvariable);
array(1) {
["hello"]=>
string(33) "Hello world Hello world Hell "
}
php > echo json_encode($myvariable);
{"hello":"Hello world Hello world Hell\ud83d\ude04 "}
php >
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
984 次 |
| 最近记录: |