我有两个字符串,我想将其限制为前25个字符。有没有办法去掉第25个字符之后的文字,然后加上一个...到字符串的末尾?
所以'12345678901234567890abcdefg‘会变成'12345678901234567890abcde...’其中'fg‘被截断。
发布于 2009-08-06 20:33:59
我可以修改一下帕兰的代码吗?
$truncated = (strlen($string) > 20) ? substr($string, 0, 20) . '...' : $string;
这不会添加“...”如果它更短的话。
发布于 2009-08-06 20:38:25
为了避免在单词中间进行剪切,您可能希望尝试使用wordwrap
函数;我想,可以这样做:
$str = "this is a long string that should be cut in the middle of the first 'that'";
$wrapped = wordwrap($str, 25);
var_dump($wrapped);
$lines = explode("\n", $wrapped);
var_dump($lines);
$new_str = $lines[0] . '...';
var_dump($new_str);
$wrapped
将包含:
string 'this is a long string
that should be cut in the
middle of the first
'that'' (length=74)
$lines
数组将如下所示:
array
0 => string 'this is a long string' (length=21)
1 => string 'that should be cut in the' (length=25)
2 => string 'middle of the first' (length=19)
3 => string ''that'' (length=6)
最后,您的$new_string
:
string 'this is a long string' (length=21)
使用子字符串,如下所示:
var_dump(substr($str, 0, 25) . '...');
你会得到:
string 'this is a long string tha...' (length=28)
这看起来不是很好:-(
不过,祝你玩得开心!
发布于 2009-08-06 20:31:02
很快的,
$truncated = substr('12345678901234567890abcdefg', 0, 20) . '...'
https://stackoverflow.com/questions/1241224
复制相似问题