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

时间:2011-04-27 00:49:35

标签: php regex preg-replace

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

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

$str = trim(preg_replace('|\\s*(?:' . preg_quote($delimiter) . ')\\s*|', $delimiter, $str));

4 个答案:

答案 0 :(得分: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
);

答案 1 :(得分:0)

以下是您问题的答案:

//drop all characters except digits and commas
    preg_match_all('/[\\d,]/', $subject, $result, PREG_PATTERN_ORDER);
    $result = implode('', $result[0]);

//strip the empty or trailing commas
    if( preg_match('/^,*(\\d.*?\\d),*$/', $result, $regs) ){
        $result = $regs[1];
    }

但您可能想要使用此功能吗?

听起来像我曾经写过的一个函数。请参阅:https://github.com/homer6/altumo/blob/master/source/php/Validation/Arrays.php

/**
* Ensures that the input is an array or a CSV string representing an array.
* If it's a CSV string, it converts it into an array with the elements split 
* at the comma delimeter.  This method removes empty values. 
* 
* Each value must be a postitive integer.  Throws and exception if they aren't
* (doesn't throw on empty value, just removes it).  This method will santize
* the values; so, if they're a string "2", they'll be converted to int 2.
* 
* 
* Eg.
*     sanitizeCsvArrayPostitiveInteger( '1,2,,,,3' );   //returns array( 1, 2, 3 );
*     sanitizeCsvArrayPostitiveInteger( array( 1, 2, 3 ) );   //returns array( 1, 2, 3 );
*     sanitizeCsvArrayPostitiveInteger( array( 1, "hello", 3 ) );   //throws Exception
*     sanitizeCsvArrayPostitiveInteger( '1,2,,"hello",,3' );   //throws Exception
* 
* @param mixed $input
* @throws Exception //if $input is not null, a string or an array
* @throws Exception //if $input contains elements that are not integers (or castable as integers)
* @return array
*/
static public function sanitizeCsvArrayPostitiveInteger( $input );

答案 2 :(得分:0)

我知道这不是你在寻找的地方,但是在我尝试的时候它会正确地返回字符串格式。

$string = ", 3,,,,, , 2 4 , , 3 , 2 4 ,,,,,";
//remove spaces
$string = preg_replace("[\s]","",$string);
// remove commas
$array = array_filter(explode(",",$string));
// reassemble
$string = implode(",",$array);

print_r($string);

返回3,24,3,24

答案 3 :(得分:0)

这是我提出的功能,在每个人的帮助下。它适用于逗号,但不适用于任何其他分隔符。

if (!function_exists('explode_trim_all')) {
  function explode_trim_all($str, $delimiter = ',') {
    if ( is_string($delimiter) ) {
      $str = preg_replace(
        array(
          '/[^\d'.$delimiter.']/', // Matches anything that's not a delimiter or number.
          '/(?<='.$delimiter.')'.$delimiter.'+/', // Matches consecutive delimiters.
          '/^'.$delimiter.'+/',                   // Matches leading delimiters.
          '/'.$delimiter.'+$/'                    // Matches trailing delimiters.
        ),
        '',              // Remove all matched substrings.
        $str
      );
      return explode($delimiter, $str);
    }
    return $str;
  }
}
相关问题