簡體   English   中英

正則表達式僅允許字符串中的整數和逗號

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

有誰知道preg_replace對於一個字符串只允許整數和逗號是什么? 我想刪除所有空格,字母,符號等,所以剩下的就是數字和逗號,但字符串中沒有任何前導或訓練逗號。 (例如:5,7,12)

以下是我現在使用的內容,它只刪除逗號前后的空格,但允許其他任何內容,我想。

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

這應該做你需要的:

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

以下是您的問題的答案:

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

我知道這不是你在尋找什么,但它在我嘗試過的所有時間都正確地返回了字符串格式。

$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

這是我提出的功能,在每個人的幫助下。 它適用於逗號,但不適用於任何其他分隔符。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM