我正在寻找一种方法来限制在PHP中的字符串,并加上...在最后,如果字符串太长。限制字符串长度
限制字符串长度
回答
您可以使用类似于下面的东西:
if (strlen($str) > 10)
$str = substr($str, 0, 7) . '...';
You might want to take a look at this answer如果你不想拆分单词。
如果您不关心分词,那么只需使用php substr function即可。
用php online manual's string functions做一点小作业。 你会想在比较设置使用strlen
,substr
如果你需要削减它,并与连接符"..."
或"…"
要截断由最高限额提供的字符串不破坏一个字使用:
/**
* 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)
{
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 4.0.6 ,对于同样的事情
功能MB功能 _ strimwidth可用于您的要求
<?php
echo mb_strimwidth("Hello World", 0, 10, "-yahooo!-");
//Hello W-yahooo!-
?>
它有更多的选择,虽然,这里是这个mb_strimwidth
文档wordwrap()函数也可以是有用的:http://www.w3schools.com/php/func_string_wordwrap.asp – 2016-05-04 16:49:05
但个人而言,我更喜欢使用:$ s = preg_replace('/ \ s +?(\ S +)?$ /','',substr($ s,$ START,$ LIMIT)); – 2016-05-04 17:56:43
@CyrilJacquart更好地避免使用正则表达式,只要它不是必需的。 – 2016-06-10 10:30:59
以另一种方式来限制PHP中的字符串并添加阅读文本或像'...'使用以下代码
if (strlen(preg_replace('#^https?://#', '', $string)) > 30) {
echo substr(preg_replace('#^https?://#', '', $string), 0, 35).'…';
}
在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;
}
$值= str_limit;(7 '这个字符串是真的很长。')
//这个ST ...
- 1. 限制属性的字符串长度
- 2. C++ - 限制字符串长度
- 3. Ajax字符串长度限制?
- 4. 限制XSLT中的字符串长度
- 5. 限制FreeMarker中的字符串长度
- 6. 字符长度限制$ _GET?
- 7. DataTable中的字符串DataColunm:限制字符串的长度
- 8. 使用MYSQL将字符串长度限制为最小字符
- 9. 使用角度2 /离子限制字符串长度2
- 10. 字符串长度有限的strtod
- 11. javascript参数字符长度限制?
- 12. PostgreSQL字符变长度限制
- 13. 限制在网页上显示的字符串长度
- 14. 是否有PHP curl返回值的字符串长度限制?
- 15. 有没有办法限制jaxb类中字符串的长度?
- 16. 正则表达式来限制字符串长度
- 17. Android中是否存在字符串长度限制?
- 18. AngularJS和Handlebars限制输出的字符串长度
- 19. ios phonegap中查询字符串是否有长度限制?
- 20. 使用VBA对字符串长度有限制吗?
- 21. 如何用jquery限制多个元素的字符串长度?
- 22. 使用$ .getJSON时是否存在字符串长度限制?
- 23. 属性文件字符串长度限制(JAVA)
- 24. 在vba中查询字符串长度限制?
- 25. UITextField - 限制文本长度不受字符数的限制
- 26. 将Python输入字符串限制为某些字符和长度
- 27. 正则表达式来限制字符串的长度与新行字符
- 28. 限制JSON字符串深度
- 29. 角度限制输入[数字]长度
- 30. 时刻字符串长度
您可能会发现['S($ STR) - >截断($长度)'](https://github.com/delight-im/PHP-Str/ blob/8fd0c608d5496d43adaa899642c1cce047e076dc/src/Str.php#L233)甚至['s($ str) - > truncateSafely($ length)'](https://github.com/delight-im/PHP-Str/blob/8fd0c608d5496d43adaa899642c1cce047e076dc /src/Str.php#L246)很有帮助,在[这个独立的库](https://github.com/delight-im/PHP-Str)中找到。 – caw 2016-07-27 01:01:21