php 限定字符长度,php-限制字符串长度

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值