如何在不切断单词的情况下截断php中的字符串?

时间:2013-07-06 22:11:26

标签: php string

我正在为后续案例寻找解决方案。 我有一个字符串

"This is a long string of words"

我只想使用前几个单词,但是如果我只是在第20个字符之后删除所有内容,它将如下所示:

"This is a long strin"

我可以先抓3个字

implode(' ', array_slice(explode(' ', "This is a long string of words"), 0, 3));

但在某些情况下,3个字会变得太短“I I I”。

如何在第20个字符之前尽可能多地抓住单词?

2 个答案:

答案 0 :(得分:6)

echo array_shift(explode("\n", wordwrap($text, 20)));

文档:

答案 1 :(得分:2)

在我用PHP给出答案之前,您是否考虑过以下CSS解决方案?

overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;

这将导致文本在最合适的位置被切断,省略号...标记为截止。

如果这不是您正在寻找的效果,请尝试以下PHP:

$words = explode(" ",$input);
// if the first word is itself too long, like hippopotomonstrosesquipedaliophobia‎
// then just cut that word off at 20 characters
if( strlen($words[0]) > 20) $output = substr($words[0],0,20);
else {
    $output = array_shift($words);
    while(strlen($output." ".$words[0]) <= 20) {
        $output .= " ".array_shift($words);
    }
}
相关问题