我有一个用PHP编写的代码片段,它从数据库中提取一个文本块并将其发送到网页上的小部件.原始文本块可以是冗长的文章或短句或短句; 但对于这个小部件,我不能显示超过200个字符.我可以使用substr()来切断200个字符的文本,但结果会在单词中间切断 - 我真正想要的是在200个字符之前在最后一个单词的末尾剪切文本.
我之前在这里问过类似的问题,但我需要知道这个小调整是否可行.我想将一个字符串缩短为100个字符并使用$small = substr($big, 0, 100);它.但是,这只需要前100个字符,并不关心它是否会破坏一个单词.
有没有办法接受一个字符串的前100个字符但确保你不会破坏一个字?
例:
$big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!"
$small = some_function($big);
echo $small;
// OUTPUT: "This is a sentence that has more than 100 characters in it, and I want to return a string of only"
Run Code Online (Sandbox Code Playgroud)
有没有办法用PHP做到这一点?