php-限制字符串长度
我正在寻找一种方法来限制php中的字符串,并在字符串过长时在末尾添加...。
Belgin Fish asked 2020-01-08T02:40:56Z
9个解决方案
123 votes
您可以使用类似于以下内容的东西:
if (strlen($str) > 10)
$str = substr($str, 0, 7) . '...';
bramp answered 2020-01-08T02:41:15Z
21 votes
从PHP 4.0.6起,有一个功能完全相同
mb_strimwidth函数可用于您的要求
echo mb_strimwidth("Hello World", 0, 10, "...");
//Hello W...
?>
它确实有更多选择,这里是此mb_strimwidth的文档
Sarath Sadasivan Pillai answered 2020-01-08T02:41:44Z
6 votes
您可以使用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函数。
echo substr($str, 0, 28) . '...';
Sev answered 2020-01-08T02:42:13Z
3 votes
使用php在线手册的字符串函数做一些功课。您需要在比较设置中使用"...",在需要时使用"..."进行剪切,并使用"..."或"…"的串联运算符
dlamblin answered 2020-01-08T02:42:33Z
1 votes
在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;
}
geckob answered 2020-01-08T02:42:53Z
1 votes
要截断最大限制提供的字符串而又不打断单词,请使用以下命令:
/**
* 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;
}
crmpicco answered 2020-01-08T02:43:14Z
0 votes
以另一种方式限制php中的字符串并添加阅读更多文本或使用以下代码,例如“ ...”
if (strlen(preg_replace('#^https?://#', '', $string)) > 30) {
echo substr(preg_replace('#^https?://#', '', $string), 0, 35).'…';
}
PCMShaper answered 2020-01-08T02:43:34Z
0 votes
第二个参数是字符串的起始位置,第三个参数需要显示多少个字符
$title = "This is for testing string for get limit of string This is for testing string for get limit of string This is for testing string for get limit of string This is for testing string for get limit of string";
echo substr($title,0,50);
Naeem Ijaz answered 2020-01-08T02:43:54Z
-3 votes
$ value = str_limit('这个字符串真的很长。',7);
//这个...
Paul Caleb answered 2020-01-08T02:44:18Z