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

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

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

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

4

2 回答 2

0

try this

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;
}
于 2013-07-10T01:57:06.390 回答
0

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

function fix_comma($str) {
    preg_match_all('~\+?+\d++\+?+~', $str, $matches);
    return implode(',', $matches[0]);
}
于 2013-07-10T02:03:18.540 回答