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.
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With