Регулярное выражение, позволяющее только целые числа и запятые в строке

Кто-нибудь знает, что 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; } }