我有一个字符串
$str = 'one,,two,three,,,,,four';
我想像这样排列(print_r的输出)
Array ( [0] => one,two,three,four )
我的代码是
$str = 'one,,two,three,,,,,four';
$str_array = explode(',', $str);
print_r($str_array);
但是没有工作因为多个逗号并排。我怎么能解决这个问题?
答案 0 :(得分:2)
您可以使用array_filter函数从数组中删除空元素。
所以你的代码应该是:
$str = 'one,,two,three,,,,,four';
$str_array = array_filter(explode(',', $str));
print_r($str_array);
已编辑的代码
$str = 'one,,two,three,,,,,four';
$str_array = implode(',',array_filter(explode(',', $str)));
echo $str_array; // you will get one,two,three,four
答案 1 :(得分:1)
您可以使用preg_replace
删除多个逗号作为
$str = 'one,,two,three,,,,,four';
echo $str_new = preg_replace('/,+/', ',', $str);// one,two,three,four
$str_array = explode(' ', $str_new);
print_r($str_array);//Array ( [0] => one,two,three,four )
答案 2 :(得分:1)
试试这个
<?php
$string = 'one,,two,three,,,,,four';
$new_array = array_filter(explode(',', $string));
$final_array[] = implode(',',$new_array);
print_r($final_array);
?>
OUTPUT: Array ( [0] => one,two,three,four )
答案 3 :(得分:0)
<?php
$string = 'one,,two,three,,,,,four';
$result = array(preg_replace('@,+@', ',', $string));
print_r($result);
输出:
Array ( [0] => one,two,three,four )