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

后端 未结 4 1207
心在旅途
心在旅途 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: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 );
    

提交回复
热议问题