正则表达式仅允许字符串中包含整数和逗号
有谁知道 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这应该可以满足您的需要:
This should do what you need:
这是您问题的答案:
但是您可能想改用这个函数?
听起来像是我曾经写过的一个函数。请参阅: https://github.com/homer6/altumo /blob/master/source/php/Validation/Arrays.php
Here's the answer to your question:
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
我知道这并不是您真正想要的,但每次我尝试它时它都会返回格式正确的字符串。
返回
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.
returns
3,24,3,24
这是我在大家的帮助下想出的功能。它适用于逗号,但不适用于任何其他分隔符。
This is a the function I came up with, with everyone's help. It works fine for commas, but not any other delimiters.