user3391751
user3391751

Reputation:

How to replace multiple character from single one?

My variable contains string like "1,5,4,,,,6,4,9,12,55,,,4,,,,9,,,,," and I want to get output like "1,5,4,6,4,9,12,55,4,9". I know there are many ways to do this in C#. but, Now I am doing code in php. So, I could not use any .net feature.

There is a loop which is processing on all lines to remove unnecessary comma and the length of list might be more than 15000.

I don't have enough knowledge about php. I am a self learner.

Upvotes: 1

Views: 74

Answers (3)

Mostafa Talebi
Mostafa Talebi

Reputation: 9183

Simple. Using regular expression.

$v = "a,b,,,,,,c,d,f,,,,t";
 $x = preg_replace("/,{2,}/", ",", $v);
 echo $x;

And the result:

a,b,c,d,f,t

Note:

PHP Regular Expression is highly optimized and would probably takes less time (hence resources) to finish the process (than takes array explode..)

Upvotes: 1

Kamehameha
Kamehameha

Reputation: 5473

preg_replace should work -

$pattern = Array('/,{2,}/','/,{1,}$/');
$replace = Array(",","");
$string = "1,5,4,,,,6,4,9,12,55,,,4,,,,9,,,,,";
$res = preg_replace($pattern,$replace,$string);
var_dump($res);
/** OUTPUT **/
//string '1,5,4,6,4,9,12,55,4,9' (length=22)

Upvotes: 0

xdazz
xdazz

Reputation: 160833

Explode it, remove the empty value, and implode it again.

$str = "1,5,4,,,,6,4,9,12,55,,,4,,,,9,,,,,"; 
$str = implode(',', array_filter(explode(',', $str)));

Upvotes: 4

Related Questions