在逗号分隔列表中删除引用字符串中的逗号

时间:2012-04-19 06:52:23

标签: php string double-quotes

我有一个字符串

$str = '1,2,3,4,5,"6,000",7,8,9';

如何清理它:

'1,2,3,4,5,6000,7,8,9'

4 个答案:

答案 0 :(得分:3)

http://php.net/str-getcsv

$items = str_getcsv($str);
$items = array_map (
  function ($item) { str_replace(',', '', $item); },
  $items;
);

如果您愿意,可以将它们再次合并在一起

$str = implode(',', $items);

答案 1 :(得分:0)

尝试这样的事情(对于PHP< 5.3):

$dst = array();
$str = '1,2,3,4,5,"6,000",7,8,9';

$state = false;
$buffer = '';
for ($i = 0, $lim = strlen($str); $i < $lim; $i += 1) {
  $char = $str[$i];

  switch ($char) {
    case ',':
      if (!$state) {
        $dst[] = $buffer;
        $buffer = '';
      }
      break;

    case '"':
      $state = !$state;
      break;

    default:
      $buffer .= $char;
  }
}

$dst[] = $buffer;

print_r($dst);

答案 2 :(得分:0)

使用此:

$str = '1,2,3,4,5,"6,000",7,8,9';
$pattern='/"(\d+),(\d+)"/';
$replacement='${1}$2';

echo preg_replace($pattern, $replacement, $str );

感谢: - )

答案 3 :(得分:-1)

<?php
$str = '1,2,3,4,5,"6,000",7,8,9';
echo $str;
echo str_replace('"','',$str);
?>