php preg_replace更改所以它不会删除加号+

时间:2013-07-10 01:46:11

标签: php regex preg-replace

这是我到目前为止的代码:

function fix_comma($str) {
  $str = preg_replace('/[^0-9,]|,[0-9]*$/', ',', $str); 
  $str = preg_replace(
      array(
        '/[^\d,]/',    // Matches anything that's not a comma or number.
        '/(?<=,),+/',  // Matches consecutive commas.
        '/^,+/',       // Matches leading commas.
        '/,+$/'        // Matches trailing commas.
      ),
      '',              // Remove all matched substrings.
      $str
    );
  return $str;
}

很好地将文本区域输入转换为逗号分隔的数字组:

103 ,,, 112 - 119 asdf 125变成103,112,119,125

有时用户会希望在一个或多个数字中包含加号:

103 - 112 - 119 - 125+需要变成103,112,119,125+ 要么 103,112,119,+ 125需要变成103,112,119,+ 125

有人可以修复该功能,以便如果包含加号,它不会从最终字符串中删除吗?

2 个答案:

答案 0 :(得分:0)

试试这个

function fix_comma($str) {
  $str = preg_replace('/[^0-9,\+]|,[0-9]*$/', ',', $str); 
  $str = preg_replace(
      array(
        '/[^\d,\+]/',    // Matches anything that's not a comma, + or number.
        '/(?<=,),+/',  // Matches consecutive commas.
        '/^,+/',       // Matches leading commas.
        '/,+$/'        // Matches trailing commas.
      ),
      '',              // Remove all matched substrings.
      $str
    );
  return $str;
}

答案 1 :(得分:0)

对于使用preg_match_all的情况似乎更简单:

function fix_comma($str) {
    preg_match_all('~\+?+\d++\+?+~', $str, $matches);
    return implode(',', $matches[0]);
}