Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
对于我需要检查字符串是否不超过给定长度并且如果它超过然后截断并添加省略号的情况,我通常使用如下函数但想知道是否不能在一行中做到这一点,preg_replace 可能吗?
function truncate($str, $length){ if (strLen($str) > $length) { $str = substr($str, 0, $length) . ' ...'; } return $str; }
使用内联 if:
return strLen($str) > $length ? substr($str, 0, $length) . ' ...' : $str;
如果您正在寻找正则表达式解决方案:
function truncate($str, $length) { return preg_replace('/(.{'.(int)$length.'}).+/s', '$1 ...', $str); }