如何从字符串中获取第一个x字符,而不切断最后一个单词? [英] How to get first x chars from a string, without cutting off the last word?
问题描述
我在变量中包含以下字符串.
I have the following string in a variable.
Stack Overflow is as frictionless and painless to use as we could make it.
我想从上述行中获取前28个字符,因此通常如果我使用 substr ,那么它将为我提供Stack Overflow is as frictio
此输出,但我希望将其输出为:
I want to fetch first 28 characters from the above line, so normally if I use substr then it will give me Stack Overflow is as frictio
this output but I want output as:
Stack Overflow is as...
PHP中是否有任何预制函数可以执行此操作,或者请向我提供PHP中的代码?
Is there any pre-made function in PHP to do so, Or please provide me code for this in PHP?
已
我想要从字符串中总共28个字符不打断一个单词,如果它返回的字符数少于28个而又不打断一个单词,那很好.
I want total 28 characters from the string without breaking a word, if it will return me few less characters than 28 without breaking a word, that's fine.
推荐答案
您可以使用 wordwrap()
函数,然后在换行符上爆炸并进入第一部分:
You can use the wordwrap()
function, then explode on newline and take the first part:
$str = wordwrap($str, 28);
$str = explode("\n", $str);
$str = $str[0] . '...';
这篇关于如何从字符串中获取第一个x字符,而不切断最后一个单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!