正则表达式仅允许字符串中的整数和逗号

Boo*_*ofo 4 php regex preg-replace

有谁知道preg_replace对于一个字符串只允许整数和逗号是什么?我想删除所有空格,字母,符号等,所以剩下的就是数字和逗号,但字符串中没有任何前导或训练逗号.(例如:5,7,12)

以下是我现在使用的内容,它只删除逗号前后的空格,但允许其他任何内容,我想.

$str = trim(preg_replace('|\\s*(?:' . preg_quote($delimiter) . ')\\s*|', $delimiter, $str));
Run Code Online (Sandbox Code Playgroud)

小智 13

这应该做你需要的:

$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
);
Run Code Online (Sandbox Code Playgroud)