我正试图从数组的元素中创建一个字符串。这是我的阵列:
$arr = array ( 1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four' );
现在我想要这个输出:
one, two, three and four
正如您在上面的输出中看到的,默认的分隔符是,
,最后一个分隔符是and
。
好吧,有两个PHP函数可以做到这一点,join()和内爆()。但并没有一个不能接受不同的分隔符作为最后一个。我该怎么做?
注意:我可以这样做:
$comma_separated = implode(", ", $arr);
preg_replace('/',([^,]+)$/', ' and $1', $comma_separated);
在线演示
现在我想知道有没有没有没有regex的解决方案?
您可以使用foreach并构建自己的内爆();
function implode_last( $glue, $gluelast, $array ){
$string = '';
foreach( $array as $key => $val ){
if( $key == ( count( $array ) - 1 ) ){
$string .= $val.$gluelast;
}
else{
$string .= $val.$glue;
}
}
//cut the last glue at the end
return substr( $string, 0, (-strlen( $glue )));
}
$array = array ( 1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four' );
echo implode_last( ', ', ' and ', $array );
如果数组以索引0开头,则必须设置count( $array )-2
。
试试这个:
$arr = array ( 1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four' );
$first_three = array_slice($arr, 0, -1);
$string_part_one = implode(", ", $first_three);
$string_part_two = end($arr);
echo $string_part_one.' and '.$string_part_two;
希望这能有所帮助。