使用substr和串联的PHP省略号 [英] PHP ellipsis using substr and concatenation

查看:53
本文介绍了使用substr和串联的PHP省略号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    foreach($products as $val)
    {
        $name = $val["name"];

        if(strlen($name) > 5){
             $name = substr($name,0,5) . '..';
        }

}

我有一个字符串列表,并且我想使用PHP在其末尾添加点点,但是上面的代码返回0?

I have a list of string, and I want to add dot dot at the end of it using PHP, but above code return 0?

推荐答案

进行更改,您需要在foreach中引用& 副本。

If you want to make changes you need to reference & the copy in the foreach.

示例:

foreach($products as &$val) {
                 //  ^ reference
    if(strlen($val['name']) > 5) {
        $val['name'] = substr($val['name'], 0, 5) . ' ...';
    }
}

或者,如果您对这种方式不满意,也可以使用foreach的键将其直接指向该索引。

Or if you are not comfortable this way, could also use the key of the foreach to point it directly to that index.

foreach($products as $key => $val) {
    if(strlen($val['name']) > 5) {
        $products[$key]['name'] = substr($val['name'], 0, 5) . ' ...';
               // ^ use $key
    }
}

最后,如果您根本不想要任何更改(仅输出echo),则此操作:

And lastly, if you do not want any changes at all (just output echo), then this:

foreach($products as $key => $val) {
    $name = $val['name'];
    if(strlen($name) > 5) {
        $name = substr($name['name'], 0, 5) . '...';
    }
    echo $name; // you forgot to echo
}

这篇关于使用substr和串联的PHP省略号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆