Replace the last comma with an & sign

后端 未结 8 1335
小鲜肉
小鲜肉 2020-12-09 23:21

I have searched everywhere but can\'t find a solution that works for me.

I have the following:

$bedroom_array = array($studio, $one_bed, $two_bed, $t         


        
相关标签:
8条回答
  • 2020-12-09 23:47

    Pop off the last element, implode the rest together then stick the last one back on.

    $bedroom_array = array('studio', 'one_bed', 'two_bed', 'three_bed', 'four_bed');
    $last = array_pop($bedroom_array);
    $string = count($bedroom_array) ? implode(", ", $bedroom_array) . " & " . $last : $last;
    

    Convert & to the entity & if necessary.

    0 讨论(0)
  • 2020-12-09 23:49

    A one-liner alternative, that will work for any size array ($b = $bedroom_array):

    echo count($b) <= 1 ? reset($b) : join(', ', array_slice($b, 0, -1)) . " & " . end($b); 
    
    0 讨论(0)
  • 2020-12-10 00:02

    if you have comma separated list of words you may use:

    $keyword = "hello, sadasd, sdfgdsfg,sadfsdafsfd, ssdf, sdgdfg";
    $keyword = preg_replace('/,([^,]*)$/', ' & \1', $keyword);
    echo $keyword;

    it will output: hello, sadasd, sdfgdsfg,sadfsdafsfd, ssdf & sdgdfg

    0 讨论(0)
  • 2020-12-10 00:06
    <?php
    $string = "3, 4, 5";
    echo $string = preg_replace('/,( \d)$/', ' &\1', $string);
    ?>
    
    0 讨论(0)
  • 2020-12-10 00:08
    function fancy_implode($arr){
        array_push($arr, implode(' and ', array_splice($arr, -2)));
        return implode(', ', $arr);
    }
    

    I find this easier to read/understand and use

    • Does not modify the original array
    • Does not use regular expressions as those may fail if strings in the array contain commas, there could be a valid reason for that, something like this: array('Shirts (S, M, L)', 'Pants (72 x 37, 72 x 39)');
    • Delimiters don't have to be of the same length as with some of the other solutions
    0 讨论(0)
  • 2020-12-10 00:08
    $bedroom_list = implode(", ", array_filter($bedroom_array));
    
    $vars =  $bedroom_list;
    
    $last = strrchr($vars,",");
    
    $last_ = str_replace(",","&",$last);
    
    echo str_replace("$last","$last_",$vars);
    
    0 讨论(0)
提交回复
热议问题