PHP - 如何截断由 foreach 循环形成的字符串?
假设我的视图中有以下循环
foreach ($value as $row):
echo $row['name'] . ', ';
endforeach;
这会在浏览器中输出这样的字符串
盖迪、李、尼尔、皮尔特、亚历克斯
我想知道是否有人可以建议一种在 n
个字符处截断此字符串的方法,例如
盖迪、李、内...
由于字符串是从循环中输出的,所以我不确定如何在这个 foreach
周围包装一个截断函数。
感谢您的帮助!
示例截断函数
function truncate_text($text, $nbrChar, $append='...') {
if(strlen($text) > $nbrChar) {
$text = substr($text, 0, $nbrChar);
$text .= $append;
}
return $text;
}
Say I have the following loop in my view
foreach ($value as $row):
echo $row['name'] . ', ';
endforeach;
This outputs a string like this in my browser
Geddy, Lee, Neil, Peart, Alex,
I wonder if anyone can suggest a method to truncate this string at n
characters, for example
Geddy, Lee, Ne...
Since the string is being output from the loop I am unsure how to wrap a truncate function around this foreach
.
Thanks for helping!
sample truncate function
function truncate_text($text, $nbrChar, $append='...') {
if(strlen($text) > $nbrChar) {
$text = substr($text, 0, $nbrChar);
$text .= $append;
}
return $text;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为什么不将行值保存到变量中并截断该变量并仅回显该变量?
Why not save the row values to a variable and truncate that variable and just echo that?
首先,
foreach
不是必需的。其次,如果需要,我们可以非常简单地截断它。这还有一个好处,就是不会留下难看的尾随逗号。
First up, the
foreach
is not required. Second, we can then truncate it if required quite simply.This also has the benefit of not leaving an ugly trailing comma.
然后在 foreach 中你可以这样做,
现在
$name
将输出截断的文本。还可以考虑在循环或条件中使用方括号,虽然这不是必需的,但它在调试代码时会对您有很大帮助,因为使用方括号 {} 可以正确缩进代码。
and then in the foreach you can do it like this
now
$name
will output truncated text.also consider using brackets for loops, or conditions, although it is not necessary but it will help you a lot while debugging the code as using brackets {} can indent your code properly.
您可以使用
break
来完成此操作。这样做的(次要)优点是您不必遍历整行。
You can do this with
break
The (minor) advantage of this is that you don't have to iterate through the entire row.