Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace the last comma with an & sign

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?

like image 585
iain Avatar asked Oct 07 '11 13:10

iain


2 Answers

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.

like image 89
Michael Berkowski Avatar answered Oct 19 '22 02:10

Michael Berkowski


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

like image 41
codefreak Avatar answered Oct 19 '22 01:10

codefreak