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

后端 未结 4 1208
心在旅途
心在旅途 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;
      }
    }
    

提交回复
热议问题