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

发布于 2024-11-04 03:50:52 字数 265 浏览 1 评论 0原文

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

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

绝情姑娘 2024-11-11 03:50:52

这应该可以满足您的需要:

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

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
);
为你拒绝所有暧昧 2024-11-11 03:50:52

这是您问题的答案:

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

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 );
凉城凉梦凉人心 2024-11-11 03:50:52

我知道这并不是您真正想要的,但每次我尝试它时它都会返回格式正确的字符串。

$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

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

隐诗 2024-11-11 03:50:52

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

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

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;
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文