Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

php - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...