限制字符串长度

时间:2010-06-10 23:32:11

标签: php string

我正在寻找一种方法来限制php中的字符串,如果字符串太长,最后添加... ...

10 个答案:

答案 0 :(得分:114)

您可以使用类似下面的内容:

if (strlen($str) > 10)
   $str = substr($str, 0, 7) . '...';

答案 1 :(得分:18)

php 4.0.6 ,有一个完全相同的功能

功能 mb _ strimwidth 可用于您的需求

<?php
echo mb_strimwidth("Hello World", 0, 10, "...");
//Hello W...
?>

它确实有更多选项,这里是此mb_strimwidth

的文档

答案 2 :(得分:6)

你可以使用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) . '...';

答案 3 :(得分:3)

php online manual's string functions做一些小作业。 您需要在比较设置strlen中使用substr,以便在需要时使用{{3}},并使用"...""&hellip;"

连接运算符

答案 4 :(得分:1)

要截断由最大限制提供的字符串而不会破坏单词,请使用:

/**
 * 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;
}

答案 5 :(得分:1)

在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;
}

答案 6 :(得分:0)

以另一种方式限制php中的字符串并添加readmore文本或类似&#39; ...&#39;使用下面的代码

if (strlen(preg_replace('#^https?://#', '', $string)) > 30) { 
    echo substr(preg_replace('#^https?://#', '', $string), 0, 35).'&hellip;'; 
}

答案 7 :(得分:0)

第二个参数是字符串的起始位置,第三个参数需要显示多少个字符

$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);

答案 8 :(得分:-1)

$res = explode("\n",wordwrap('12345678910', 8, "...\n",true))[0];

// $res will be  : "12345678..."

答案 9 :(得分:-3)

$ value = str_limit('这个字符串真的很长。',7);

//这个......