replace every second comma of string using php

前端 未结 6 1450
执念已碎
执念已碎 2021-01-06 04:54

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.

6条回答
  •  情话喂你
    2021-01-06 05:28

    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
    

提交回复
热议问题