即使strlen在可接受的范围内,这个正则表达式也会切断字符串中的最后一个单词

Reg*_*dit 2 php regex preg-replace substr

$theExcerpt = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis'

$theExcerptAppend = (strlen($theExcerpt) > 156) ? '...' : '';
$theExcerpt = preg_replace('/\s+?(\S+)?$/', '', substr($theExcerpt, 0, 156));
$theExcerpt .= $theExcerptAppend;
Run Code Online (Sandbox Code Playgroud)

只要输入短语长度超过156个字符,脚本就可以正常工作.然而,当长度小于156(因为它是在这里154),在最后一个字被放下,即使字符串,包括字,仍低于156.

注意:我不希望字符串在单词的中间终止,但是如果单词的包含不超过156的strlen值,则应该包含它.

Cri*_*isp 5

使用substrstrrpos

if (strlen($theExcerpt) > 156) {
    $theExceprt = substr($theExcerpt, 0, 156);
    $theExcerpt = substr($theExcerpt, 0, strrpos($theExcerpt, ' '));        
    $theExcerpt .= '...';
}
Run Code Online (Sandbox Code Playgroud)