6

我有一串这样的显示:

1235, 3, 1343, 5, 1234, 1

我需要用分号替换每隔一个逗号

IE

1235, 3; 1343, 5; 1234, 1

字符串长度将始终不同,但将遵循与上述相同的模式,即数字逗号空格数字逗号空格等。

我怎样才能用 PHP 做到这一点?可能吗?

谢谢。

4

6 回答 6

10

preg_replace()解决方案

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

输出:

1235, 3; 1343, 5; 1234, 1
于 2013-05-22T08:37:08.383 回答
7

尝试这个 :

$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);
于 2013-05-22T08:35:10.407 回答
4

尝试这个:

<?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;
}
?>

结果:

 1235, 3; 1343, 5; 1234, 1 
于 2013-05-22T08:34:34.073 回答
2

尝试这个:

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

它输出:

1235, 3; 1343, 5; 1234, 1
于 2013-05-22T08:32:34.857 回答
1

尝试这个:

$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;
于 2013-05-22T08:34:56.847 回答
1

尝试这个:

<?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;
?>
于 2013-05-22T08:39:30.787 回答