我有两个字符串,想要将它们限制在前25个字符以内。是否有一种方法可以在第25个字符之后截断文本,并在字符串末尾添加“...”?
因此,“12345678901234567890abcdefg”将变为“12345678901234567890abcde...”,其中“fg”被截断。
我可以修改pallan的代码吗?
$truncated = (strlen($string) > 20) ? substr($string, 0, 20) . '...' : $string;
如果原字符串本身就比指定长度短,则此方法不会添加省略号。
非常迅速地,
$truncated = substr('12345678901234567890abcdefg', 0, 20) . '...'
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)
使用 substr,例如:
var_dump(substr($str, 0, 25) . '...');
你会得到:
string 'this is a long string tha...' (length=28)
看起来不太好看 :-(
尽管如此,也要享受乐趣!
function truncate($str, $chars, $end = '...') {
if (strlen($str) <= $chars) return $str;
$new = substr($str, 0, $chars + 1);
return substr($new, 0, strrpos($new, ' ')) . $end;
}
使用方法:
truncate('My string', 5); //returns: My...
http://php.net/manual/zh/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, "...");
?>
输出:
Hello W...
Hello
$words=explode(' ', $string);
for($ii = 0,$j=0; $ii< 5 && $j < sizeof($words) ;$j++){
$ii += strlen($words[$j]);
$intro= $words[$j]. " ";
}
$intro.= "...";
我知道现在已经有点晚了,但如果还有其他人回到这个页面,这将会有所帮助。
这段话与IT技术无关。$str = "This string might be longer than 25 chars, or might not!";
// we are forcing to cut long words...
$wrapped = wordwrap($str, 25, "\n", 1);
var_dump($wrapped);
$lines = explode("\n", $wrapped);
var_dump($lines);
// if our $str is shorter than 25, there will be no $lines[1]
(array_key_exists('1', $lines)) ? $suffix = '...' : $suffix = '';
$new_str = $lines[0] . $suffix;
var_dump($new_str);
<?php echo substr('12345678901234567890abcdefg', 0, 20) . '...' ?>
s($str)->truncate(25)
或者s($str)->truncateSafely(25)
很有用,这两个方法都来自于这个独立的库,并且支持Unicode,第二个方法还避免了截断单词。 - caw