【问题标题】:php replace last character of specific characterphp替换特定字符的最后一个字符
【发布时间】:2019-04-27 21:30:45
【问题描述】:

我有一个数组,我想从中生成一条消息。 如果我使用join(', ', $response),我会得到file1.jpg, file2.jpg, file3.jpg。是否可以替换最后一个逗号,使消息为file1.jpg, file2.jpg AND file3.jpg

【问题讨论】:

    标签: php arrays join replace


    【解决方案1】:

    这应该有效;

    <?php 
    
    $response=['file1.jpg','file2.jpg','file3.jpg'];
    
    $response=array_reverse($response);
    
    $arr=$response[1].' AND ' .$response[0];
    for ($i=2; $i < count($response); $i++) { 
        $new[]=$response[$i];
    }
    array_push($new, $arr);
    
    echo join(", ",$new);
    

    【讨论】:

    • 太好了,你能把答案标记为正确的吗?
    【解决方案2】:

    您可以使用array_slice 来获取数组中除最后一个以外的所有元素,并为其设置特殊情况:

    function formatList($response)
    {
        if(count($response) == 0)
            return '' ;
        if(count($response) == 1)
            return $response[0] ;
        else
            return join(', ', array_slice($response, 0, count($response)-1)) . ' AND ' . end($response);
    }
    

    【讨论】:

      【解决方案3】:

      substr_replace 用位置和长度替换字符串的一部分,strrpos 查找最后一个逗号的位置。

      $response = ['file1.jpg', 'file2.jpg', 'file3.jpg'];
      $out = join(', ', $response);
      echo substr_replace($out, " AND", strrpos(($out), ','), 1);
      

      https://www.php.net/manual/en/function.substr-replace.php https://www.php.net/manual/en/function.strrpos.php

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-04
        • 1970-01-01
        • 1970-01-01
        • 2014-02-12
        相关资源
        最近更新 更多