如何为最后一项分配不同的分隔符?
How can I devote different separator for last item?
我正在尝试从数组元素创建字符串。这是我的数组:
$arr = array ( 1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four' );
现在我想要这个输出:
one, two, three and four
正如您在上面的输出中看到的,默认分隔符是 ,
,最后一个分隔符是 and
。
嗯,有两个 PHP 函数可以做到这一点,join() and implode()。但是其中 none 无法接受最后一个的不同分隔符。我该怎么做?
注意:我可以这样做:
$comma_separated = implode(", ", $arr);
preg_replace('/\,([^,]+)$/', ' and ', $comma_separated);
Online Demo
现在我想知道没有正则表达式的解决方案吗?
试试这个:
$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;
希望对您有所帮助。
您可以使用 foreach 并构建您自己的 implode();
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' );
现在我想要这个输出:
one, two, three and four
正如您在上面的输出中看到的,默认分隔符是 ,
,最后一个分隔符是 and
。
嗯,有两个 PHP 函数可以做到这一点,join() and implode()。但是其中 none 无法接受最后一个的不同分隔符。我该怎么做?
注意:我可以这样做:
$comma_separated = implode(", ", $arr);
preg_replace('/\,([^,]+)$/', ' and ', $comma_separated);
Online Demo
现在我想知道没有正则表达式的解决方案吗?
试试这个:
$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;
希望对您有所帮助。
您可以使用 foreach 并构建您自己的 implode();
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
。