Replace the last comma with &

I searched everywhere but cannot find a solution that works for me.

I have the following:

$bedroom_array = array($studio, $one_bed, $two_bed, $three_bed, $four_bed);

In this example we can say:

$studio = '1';
$one_bed = '3';
$two_bed = '3';

Then I use the implode function to put a comma between all the values:

$bedroom_list = implode(", ", array_filter($bedroom_array));
echo $bedroom_list;

Then issued:

1, 2, 3

What I want to do is find the last comma in the line and replace it with &, so it will read:

1, 2 and 3

The string will not always be so long; it can be shorter or longer, for example. 1, 2, 3, 4, etc. I studied using substr but not sure if this will work for what I need?

+5
source share
7 answers

, , .

$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;

& &, .

+24

, :

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

: hello, sadasd, sdfgdsfg, sadfsdafsfd, ssdf sdgdfg

+4

, ($ b = $bedroom_array):

echo count($b) <= 1 ? reset($b) : join(', ', array_slice($b, 0, -1)) . " & " . end($b); 
+1
function fancy_implode($arr){
    array_push($arr, implode(' and ', array_splice($arr, -2)));
    return implode(', ', $arr);
}

/

  • , , , : array('Shirts (S, M, L)', 'Pants (72 x 37, 72 x 39)');
  • Separators do not have to be the same length as with some other solutions
+1
source
$bedroom_list = implode(", ", array_filter($bedroom_array));

$vars =  $bedroom_list;

$last = strrchr($vars,",");

$last_ = str_replace(",","&",$last);

echo str_replace("$last","$last_",$vars);
0
source
<?php
$string = "3, 4, 5";
echo $string = preg_replace('/,( \d)$/', ' &\1', $string);
?>
0
source

strrpos finds the last occurrence of the specified string. $ str = '1, 2, 3';

$index = strrpos( $str, ',' ); 
if( $index !== FALSE )
    $str[ $index ] = '&'; 
0
source

All Articles