PHP截断字符串,如果长于限制,并在末尾略去一些..类似于ruby [英] php truncate string if longer than limit and put some omission at the end..similar to ruby

查看:65
本文介绍了PHP截断字符串,如果长于限制,并在末尾略去一些..类似于ruby的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在最近的php代码中多次需要此功能,因此,我正在寻找一个功能来完成这项工作,如果有的话..

I need this functionality in my recent php code many times, So I am lookin for a function to do the work, if there exists any..

如果字符串大于限制,则将其截断并放入一些省略的文本,例如...(continued) ..

If the string if bigger than the limit truncate it and put some omission text like ...(continued)..

像红宝石一样,我们在字符串上有截断功能

Like in ruby we have truncate function on string

"And they found that many people were sleeping better.".truncate(25, :omission => "... (continued)")

我可以先检查长度是否超过..然后修剪,然后串联...但是我正在寻找一些类似的功能.

I could do it by first checking the length exceeds.. then trim, then concatenation...But I am looking for some function similar..

推荐答案

function substr_with_ellipsis($string, $chars = 100)
{
    preg_match('/^.{0,' . $chars. '}(?:.*?)\b/iu', $string, $matches);
    $new_string = $matches[0];
    return ($new_string === $string) ? $string : $new_string . '…';
}

这篇关于PHP截断字符串,如果长于限制,并在末尾略去一些..类似于ruby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆