Replace the last comma with an & sign

2020-02-05 05:15发布

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, $three_bed, $four_bed);

For this example lets say:

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

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

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

This then outputs:

1, 2, 3

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

1, 2 & 3

The string will not always be this long, it can be shorter or longer, e.g. 1, 2, 3, 4 and so on. I have looked into using substr but am not sure if this will work for what I need?

7条回答
Fickle 薄情
2楼-- · 2020-02-05 05:41

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

$index = strrpos( $str, ',' ); 
if( $index !== FALSE )
    $str[ $index ] = '&'; 
查看更多
萌系小妹纸
3楼-- · 2020-02-05 05:43

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); 
查看更多
时光不老,我们不散
4楼-- · 2020-02-05 05:44
<?php
$string = "3, 4, 5";
echo $string = preg_replace('/,( \d)$/', ' &\1', $string);
?>
查看更多
家丑人穷心不美
5楼-- · 2020-02-05 05:57
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
查看更多
在下西门庆
6楼-- · 2020-02-05 06:01
$bedroom_list = implode(", ", array_filter($bedroom_array));

$vars =  $bedroom_list;

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

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

echo str_replace("$last","$last_",$vars);
查看更多
Viruses.
7楼-- · 2020-02-05 06: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

查看更多
登录 后发表回答