Regular expression to only allow whole numbers and commas in a string

后端 未结 4 1168
心在旅途
心在旅途 2020-12-19 16:19

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 le

相关标签:
4条回答
  • 2020-12-19 16:40

    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;
      }
    }
    
    0 讨论(0)
  • 2020-12-19 16:48

    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 );
    
    0 讨论(0)
  • 2020-12-19 16:55

    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

    0 讨论(0)
  • 2020-12-19 17:03

    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
    );
    
    0 讨论(0)
提交回复
热议问题