我有两个字符串,我想限制为例如前25个字符.有没有办法在第25个字符后切断文本并在字符串末尾添加...?
所以'12345678901234567890abcdefg'会变成'12345678901234567890abcde ...'其中'fg'被切断.
Tyl*_*ter 44
我可以修改pallan的代码吗?
$truncated = (strlen($string) > 20) ? substr($string, 0, 20) . '...' : $string;
Run Code Online (Sandbox Code Playgroud)
如果它更短,则不会添加'...'.
Pas*_*TIN 10
为了避免在单词中间切换,您可能想要尝试该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);
Run Code Online (Sandbox Code Playgroud)
$wrapped 将包含:
string 'this is a long string
that should be cut in the
middle of the first
'that'' (length=74)
Run Code Online (Sandbox Code Playgroud)
该$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)
Run Code Online (Sandbox Code Playgroud)
最后,你的$new_string:
string 'this is a long string' (length=21)
Run Code Online (Sandbox Code Playgroud)
使用substr,如下所示:
var_dump(substr($str, 0, 25) . '...');
Run Code Online (Sandbox Code Playgroud)
你得到了:
string 'this is a long string tha...' (length=28)
Run Code Online (Sandbox Code Playgroud)
哪个看起来不那么好:-(
还是,玩得开心!
真的很快,
$truncated = substr('12345678901234567890abcdefg', 0, 20) . '...'
Run Code Online (Sandbox Code Playgroud)
这个很短,并考虑到字边界,它不使用循环,这使得它非常有效
function truncate($str, $chars, $end = '...') {
if (strlen($str) <= $chars) return $str;
$new = substr($str, 0, $chars + 1);
return substr($new, 0, strrpos($new, ' ')) . $end;
}
Run Code Online (Sandbox Code Playgroud)
用法:
truncate('My string', 5); //returns: My...
Run Code Online (Sandbox Code Playgroud)
http://php.net/manual/en/function.mb-strimwidth.php (PHP 4 >= 4.0.6, PHP 5, PHP 7)
<?php
echo mb_strimwidth("Hello World", 0, 10, "...");
echo "<br />";
echo mb_strimwidth("Hello", 0, 10, "...");
?>
Run Code Online (Sandbox Code Playgroud)
输出:
Hello W...
Hello
Run Code Online (Sandbox Code Playgroud)