Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace every second comma of string using php

Tags:

replace

php

I have a string of that displays like this:

1235, 3, 1343, 5, 1234, 1

I need to replace every second comma with a semicolon

i.e.

1235, 3; 1343, 5; 1234, 1

The string length will always be different but will follow the same pattern as the above i.e. digits comma space digits comma space, etc.

How can I do this with PHP? Is it possible?

Thanks.

like image 831
Jack Php Avatar asked May 22 '13 08:05

Jack Php


2 Answers

Preg_replace() solution

$str = '1235, 3, 1343, 5, 1234, 1';
$str = preg_replace('/(.+?),(.+?),/', '$1,$2;', $str);
echo $str;

Output:

1235, 3; 1343, 5; 1234, 1
like image 98
Robert Avatar answered Sep 20 '22 09:09

Robert


Try this :

$str     = '1235, 3, 1343, 5, 1234, 1';
$res_str = array_chunk(explode(",",$str),2);
foreach( $res_str as &$val){
   $val  = implode(",",$val);
}
echo implode(";",$res_str);
like image 20
Prasanth Bendra Avatar answered Sep 21 '22 09:09

Prasanth Bendra