用&替换最后一个逗号.标志 [英] Replace the last comma with an & sign
问题描述
我到处搜索过,但找不到适合我的解决方案.
I have searched everywhere but can't find a solution that works for me.
我有以下内容:
$bedroom_array = array($studio, $one_bed, $two_bed, $three_bed, $four_bed);
对于此示例,请说:
$studio = '1';
$one_bed = '3';
$two_bed = '3';
然后我使用implode函数在所有值之间放置一个逗号:
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;
然后输出:
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
1, 2 & 3
字符串不一定总是那么长,它可以更短或更长,例如1、2、3、4等.我已经研究过使用substr,但是不确定是否可以满足我的需求?
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?
推荐答案
弹出最后一个元素,将其余元素合并在一起,然后再粘贴最后一个.
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.
这篇关于用&替换最后一个逗号.标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!