正则表达式只允许整数和逗号在字符串中 [英] Regular expression to only allow whole numbers and commas in a string
本文介绍了正则表达式只允许整数和逗号在字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人知道只允许整数和逗号的字符串的preg_replace是什么吗?我要去除所有空格,字母,符号等,因此剩下的就是数字和逗号,但字符串中没有任何前导或训练逗号. (例如:5、7、12)
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));
推荐答案
这应该可以满足您的需求:
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
);
这篇关于正则表达式只允许整数和逗号在字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文