我正在寻找一种方法来限制php中的字符串,如果字符串太长,最后添加...
您可以使用类似下面的内容:
if (strlen($str) > 10)
$str = substr($str, 0, 7) . '...';
从php 4.0.6开始,有一个完全相同的功能
function mb_strimwidth可以用于您的要求
<?php
echo mb_strimwidth("Hello World", 0, 10, "...");
//Hello W...
?>
它确实有更多的选择,这里是这个mb_strimwidth的文档
你可以使用wordwrap()
函数然后在换行符上爆炸并取第一部分,如果你不想分割单词。
$str = 'Stack Overflow is as frictionless and painless to use as we could make it.';
$str = wordwrap($str, 28);
$str = explode("\n", $str);
$str = $str[0] . '...';
资料来源:https://stackoverflow.com/a/1104329/1060423
如果你不关心分词,那么只需使用php substr function。
echo substr($str, 0, 28) . '...';
用php online manual's string functions做一点功课。你需要在比较设置中使用strlen
,如果需要,可以使用substr
来剪切它,并使用"..."
或"…"
连接运算符
在Laravel中,有一个字符串util函数,它以这种方式实现:
public static function limit($value, $limit = 100, $end = '...')
{
if (mb_strwidth($value, 'UTF-8') <= $limit) {
return $value;
}
return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')).$end;
}
要截断最大限制提供的字符串而不破坏单词,请使用以下命令:
/**
* truncate a string provided by the maximum limit without breaking a word
* @param string $str
* @param integer $maxlen
* @return string
*/
public static function truncateStringWords($str, $maxlen): string
{
if (strlen($str) <= $maxlen) return $str;
$newstr = substr($str, 0, $maxlen);
if (substr($newstr, -1, 1) != ' ') $newstr = substr($newstr, 0, strrpos($newstr, " "));
return $newstr;
}
另一种方法是限制php中的字符串,并使用下面的代码添加读取更多文本或类似“...”
if (strlen(preg_replace('#^https?://#', '', $string)) > 30) {
echo substr(preg_replace('#^https?://#', '', $string), 0, 35).'…';
}
$ value = str_limit('这个字符串真的很长。',7);
//这个......