Regular expression to only allow whole numbers and

2020-02-12 11:32发布

问题:

Does anyone know what the preg_replace would be for a string to only allow whole numbers and commas? I want to strip all whitespace, letters, symbols, etc, so all that is left is numbers and commas, but without any leading or training commas in the string. (Example: 5,7,12)

Here is what I am using now and it only strips whitespace before and after the commas but allows anything else, I think.

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

回答1:

This should do what you need:

$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
);


回答2:

Here's the answer to your question:

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

But you might want to use this function instead?

Sounds like a function I once wrote. See: 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 );


回答3:

I know this isn't really what you where looking for but it returns the string formatted correctly everything time I have tried it.

$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);

returns 3,24,3,24



回答4:

This is a the function I came up with, with everyone's help. It works fine for commas, but not any other delimiters.

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