相关疑难解决方法(0)

从字符串中获取前100个字符,尊重完整的单词

我之前在这里问过类似的问题,但我需要知道这个小调整是否可行.我想将一个字符串缩短为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做到这一点?

php string

65
推荐指数
6
解决办法
13万
查看次数

即使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;
Run Code Online (Sandbox Code Playgroud)

只要输入短语长度超过156个字符,脚本就可以正常工作.然而,当长度小于156(因为它是在这里154),在最后一个字被放下,即使字符串,包括字,仍低于156.

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

php regex preg-replace substr

2
推荐指数
1
解决办法
441
查看次数

标签 统计

php ×2

preg-replace ×1

regex ×1

string ×1

substr ×1