在 PHP 中缩短/截断 UTF8 字符串
我需要一个良好的快速函数,可以将字符串缩短到支持 UTF8 的设定长度。在末尾添加尾随“...”是一个优点。有人可以帮忙吗?
I need a good fast function that shortens strings to a set length with UTF8 support. Adding trailing '...' at ends is a plus. Can anyone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设安装了
mb_*
功能。键盘。
请记住,这将添加一个字符(省略号)。如果您希望将
$append
包含在截断的长度中,只需从您截断的字符串长度中减去mb_strlen($append)
即可。显然,这也会打断单词的中间部分。
更新
这是一个可以选择保留整个单词的版本...
CodePad。
如果第三个参数为 TRUE,它将保留第一个非字母字符之前的所有字母字符。
Assuming
mb_*
functions installed.CodePad.
Keep in mind this will add one character (the elipsis). If you want the
$append
included in the length that is truncated, just minus themb_strlen($append)
from the length of the string you chop.Obviously, this will also chop in the middle of words.
Update
Here is a version that can optionally preserve whole words...
CodePad.
It will preserve all letter characters up to the first non letter character if the third argument is
TRUE
.我猜你需要截断文本,所以这可能会有所帮助:
这类似于 @alex 刚刚发布的内容,但它不会破坏单词。
I guess you need to truncate text, so this may be helpful:
This is something like @alex just posted, but it does not break words.
试试这个:
$length = 100;
if(mb_strlen($text, "utf-8") > $length){
$last_space = mb_strrpos(mb_substr($text, 0, $length, "utf-8"), " ", "utf-8");
$text = mb_substr($text, 0, $last_space, "utf-8")." ...";}
干杯...
Try this:
$length = 100;
if(mb_strlen($text, "utf-8") > $length){
$last_space = mb_strrpos(mb_substr($text, 0, $length, "utf-8"), " ", "utf-8");
$text = mb_substr($text, 0, $last_space, "utf-8")." ...";}
Cheers...