This regex is cutting off the last word in the string even though strlen is within acceptable range

ぃ、小莉子 提交于 2020-01-11 11:08:46

问题


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

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.

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.


回答1:


Using substr and strrpos

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



回答2:


I think someone posted a link to a duplicate. The accepted solution was:

/^.{1,156}\b/

Now, this will ALWAYS be less than 156 chars. If the 156th char is in a middle of a word, it will cut the last word. Some change could be made to have the opposite effect though.

Note: simply apply preg_match to your string with this regex.

Edit:
Opposite effect (having more than 156 characters to get the last word):

/^.{1,155}(.)?(?(1).*?\b)/



回答3:


How about :

$theExcerpt = preg_replace('/(?=.{156})\s+?(\S+)?$/', '', substr($theExcerpt, 0, 156));

This will treat the sentence only if it is more than 156 char long.




回答4:


Try the following:

$string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus egestas, lacus non dapibus placerat, justo mi adipiscing libero, id ultrices neque metus nec lorem. Quisque vitae dui facilisis ligula tristique dapibus. Ut egestas ligula in tortor facilisis pharetra id vitae eros. Donec commodo laoreet nisi porttitor tincidunt. Donec tortor enim, pharetra in accumsan sit amet, scelerisque ac massa. Morbi massa erat, mattis non faucibus a, feugiat imperdiet lectus. Praesent tincidunt libero id enim cursus non sagittis nisl accumsan. Maecenas massa lorem, consectetur ut rhoncus ac, ullamcorper a tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque sit amet eros.';

$limit = 156;
$output = preg_replace('/^(.{'.$limit.'})(\S|\s|\w+)(.*)/', '$1$2 ...', $string);

echo $output;


来源:https://stackoverflow.com/questions/15705059/this-regex-is-cutting-off-the-last-word-in-the-string-even-though-strlen-is-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!