Tarık Akyüz Tarık Akyüz - 5 months ago 9
PHP Question

Explode function side by side same character

I have an string

$str = 'one,,two,three,,,,,four';


I want to array like this(output of print_r)

Array ( [0] => one,two,three,four )


My code is

$str = 'one,,two,three,,,,,four';
$str_array = explode(',', $str);
print_r($str_array);


But not working Because multiple commas side by side.How can i solve this problem?

Answer

You can used array_filter function to removed empty element from array.

So your code should be:

$str = 'one,,two,three,,,,,four';
$str_array = array_filter(explode(',', $str));
print_r($str_array);

Edited Code

$str = 'one,,two,three,,,,,four';
$str_array = implode(',',array_filter(explode(',', $str)));
echo $str_array; // you will get one,two,three,four