Cam*_*oft 5 php string twitter
如何在不切换单词的情况下将字符串缩短为最多140个字符.
请使用以下字符串:
$string = "This is an example string that contains more than 140 characters. If I use PHPs substring function it will split it in the middle of this word."
使用substr($string, 0, 140)我们会得到这样的东西:
This is an example string that contains more than 140 characters. If I use PHPs substring function it will split it in the middle of this wo
注意它通过单词"word"切成薄片.
我需要的是能够缩短一个字符串,同时保留整个单词但不超过140个字符.
我确实找到了以下代码,但即使它会保留整个单词,也不能保证整个字符串不超过140个字符限制:
function truncate($text, $length) {
$length = abs((int)$length);
if(strlen($text) > $length) {
$text = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $text);
}
return($text);
}
Run Code Online (Sandbox Code Playgroud)
如果字符串太长,您可以先使用substr截断字符串,然后使用正则表达式删除最后一个完整或部分单词:
$s = substr($s, 0, (140 - 3));
$s = preg_replace('/ [^ ]*$/', ' ...', $s);
Run Code Online (Sandbox Code Playgroud)
请注意,您必须使原始文本短于140个字节,因为当您添加...时,这可能会增加字符串的长度超过140个字节.
| 归档时间: |
|
| 查看次数: |
4930 次 |
| 最近记录: |