php 8.6截取含emoji、组合音标的文本预览时,可用intl的grapheme_extract按字素簇取前n个显示单元,再根据返回的下一字节偏移决定是否追加省略号。按字节substr可能切坏utf-8,按码点截取也可能拆开一个组合emoji。

PHP手册中的PHP: grapheme_extract - Manual
校验输入并按字素截取
<?php function preview(string $text,int $limit=30):string {
if ($limit<1 || $limit>500) throw new InvalidArgumentException('上限不符');
if (strlen($text)>100000 || preg_match('//u',$text)!==1) {
throw new InvalidArgumentException('文本体积或编码不符');
}
if ($text==='') return '';
$next=0;
$part=grapheme_extract($text,$limit,GRAPHEME_EXTR_COUNT,0,$next);
if ($part===false) throw new RuntimeException('字素提取失败');
return $part.($next<strlen echo preview><p style="text-align:center">@@##@@</p>
<p style="text-align:center">PHP手册中的PHP: grapheme_strlen - Manual</p>
<h2>长度限制有不同口径</h2>
<p>GRAPHEME_EXTR_COUNT限制显示字素数量,不保证结果小于某个字节数,一个家庭Emoji就可能占很多字节。若数据库字段或传输协议限制字节,可改用GRAPHEME_EXTR_MAXBYTES;预算小于第一个完整字素时可能返回空字符串。</p>
<h2>输出到网页仍需转义</h2>
<p>截取只维护文本边界,不会清理HTML。页面显示时使用合适的HTML文本编码;不要把原始用户文本或截取结果直接放入innerHTML。ICU版本也可能影响新Emoji的分段行为,应在目标环境检查实际显示。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill13222" title="Build MCP servers and clients for PHP applications with the official PHP SDK"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20e352aa140.jpg" alt="Build MCP servers and clients for PHP applications with the official PHP SDK" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill13222" title="Build MCP servers and clients for PHP applications with the official PHP SDK" class="overflowclass">Build MCP servers and clients for PHP applications with the official PHP SDK</a>
<p class="overflowclass">使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。</p>
</div>
<a rel="nofollow" href="/xiazai/skill13222" title="Build MCP servers and clients for PHP applications with the official PHP SDK" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div></strlen>

php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










