replace every second comma of string using php

380

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.

736

Answer

Solution:

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
254

Answer

Solution:

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);
600

Answer

Solution:

Try this:

<?php
$string =  '1235, 3, 1343, 5, 1234, 1';

var_dump(nth_replace($string, ',', ';', 2));

// replace all occurences of a single character with another character
function nth_replace($string, $find, $replace, $n) {
        $count = 0;
        for($i=0; $i<strlen($string); $i++) {
                if($string[$i] == $find) {
                        $count++;
                }
                if($count == $n) {
                        $string[$i] = $replace;
                        $count = 0;
                }
        }
        return $string;
}
?>

Result:

 1235, 3; 1343, 5; 1234, 1 
926

Answer

Solution:

Try this:

$s = "1235, 3, 1343, 5, 1234, 1";
$pcs = explode(',', $s);

$flag = false;
$res = '';
foreach ($pcs as $item) {
    if (!empty($res)) {
        $res .= $flag ? ',' : ';';
    }
    $flag = !$flag;
    $res .= $item;
}
die($res);

It outputs:

1235, 3; 1343, 5; 1234, 1
558

Answer

Solution:

try this:

$s = '1235, 3, 1343, 5, 1234, 1';
$is_second = false;
for ($i = 0; $i < strlen($s); $i++) {
    if ($is_second && $s[$i] == ',') {
        $s[$i] = ';';
    } elseif ($s[$i] == ',') {
        $is_second = true;
    }
}
echo $s;
729

Answer

Solution:

Try this:

<?php
    $str = "1235, 3, 1343, 5, 1234, 1";
    $data = explode(',',$str);
    $counter = 0;
    $new_str = "";
    foreach($data as $key=>$val) {
        if ($counter%2 == 0) {
            $symbol=',';
        }
        else {
            $symbol=';';
        }
        $new_str .= $val.$symbol; 
        $counter++;
    }
    echo $new_str;
    //output::1235, 3; 1343, 5; 1234, 1;
?>

People are also looking for solutions to the problem: jquery - how to draw multiple googlechart from different datatable in one php file?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.