即使 strlen 在可接受的范围内,此正则表达式也会切断字符串中的最后一个单词 [英] This regex is cutting off the last word in the string even though strlen is within acceptable range

查看:15
本文介绍了即使 strlen 在可接受的范围内,此正则表达式也会切断字符串中的最后一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$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;

只要输入的短语长度超过 156 个字符,脚本就可以正常工作.然而,当长度小于 156 时(这里是 154),最后一个单词被丢弃,即使字符串,包括单词,仍然小于 156.

As long as the input phrase length exceeds 156 characters, the script works fine. However, when the length is less than 156 (as it is here at 154), the last word in being dropped off, even if the string, including the word, is still less than 156.

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

Note: I don't want the string to terminate in the middle of a word, but if the inclusion of the word does not exceed the strlen value of 156, it should be included.

推荐答案

使用 substrstrrpos

if (strlen($theExcerpt) > 156) {
    $theExceprt = substr($theExcerpt, 0, 156);
    $theExcerpt = substr($theExcerpt, 0, strrpos($theExcerpt, ' '));        
    $theExcerpt .= '...';
}

这篇关于即使 strlen 在可接受的范围内,此正则表达式也会切断字符串中的最后一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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