数字 PIN 码字符串的过滤器数组可以采用“######”格式。或“### ###”
我有一个 PHP 字符串数组。这些字符串应该代表 6 位数字的 PIN 码,例如:
560095
前 3 位数字后有空格也被认为是有效的,例如 560 095
。
并非所有数组元素都有效。我想过滤掉所有无效的 PIN 码。
I have a PHP array of strings. The strings are supposed to represent PIN codes which are of 6 digits like:
560095
Having a space after the first 3 digits is also considered valid e.g. 560 095
.
Not all array elements are valid. I want to filter out all invalid PIN codes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,您可以为此使用正则表达式。
PHP 有一个名为 preg_grep 的函数您将正则表达式传递给它,它会返回一个新数组,其中包含 input 数组中与模式匹配的条目。
正则表达式的解释:
Yes you can make use of regex for this.
PHP has a function called preg_grep to which you pass your regular expression and it returns a new array with entries from the input array that match the pattern.
Explanation of the regex:
是的,您可以使用正则表达式来确保有 6 位数字(带或不带空格)。
玩正则表达式的一个简洁工具是 RegExr...这是我想出的 RegEx:
它与字符串
^
开头,然后是任意三个数字[0-9]{3}
,后跟可选空格\s?
,后跟另一个三个数字[0-9]{3}
,后跟字符串$
的末尾。将数组与正则表达式一起传递到 PHP 函数
preg_grep
将返回一个仅包含匹配索引的新数组。Yes, you can use a regular expression to make sure there are 6 digits with or without a space.
A neat tool for playing with regular expressions is RegExr... here's what RegEx I came up with:
It matches the beginning of the string
^
, then any three numbers[0-9]{3}
followed by an optional space\s?
followed by another three numbers[0-9]{3}
, followed by the end of the string$
.Passing the array into the PHP function
preg_grep
along with the Regex will return a new array with only matching indeces.如果您只想迭代有效响应(循环遍历它们),您始终可以使用
RegexIterator
:它的优点是不复制整个数组(它会在您需要时计算下一个数组)。因此,对于大型数组来说,它比使用
preg_grep
执行某些操作要高效得多。但如果多次迭代,它也会变慢(但对于单次迭代,由于内存使用,它应该更快)。If you just want to iterate over the valid responses (loop over them), you could always use a
RegexIterator
:It has the benefit of not copying the entire array (it computes the next one when you want it). So it's much more memory efficient than doing something with
preg_grep
for large arrays. But it also will be slower if you iterate multiple times (but for a single iteration it should be faster due to the memory usage).如果您想获取有效 PIN 码的数组,请使用 codaddict 的答案。
您还可以在仅过滤有效 PIN 的同时,使用 删除可选的空格字符,以便所有 PIN 变为 6 位数字
preg_filter
:If you want to get an array of the valid PIN codes, use codaddict's answer.
You could also, at the same time as filtering only valid PINs, remove the optional space character so that all PINs become 6 digits by using
preg_filter
:最好的答案可能取决于您的情况,但如果您想首先进行简单且低成本的检查...
之后,您同样可以继续进行一些类型检查 - 只要有效数字不以 0 开头在这种情况下可能会更困难。
如果您没有尽早失败,请继续使用已发布的正则表达式解决方案。
The best answer might depend on your situation, but if you wanted to do a simple and low cost check first...
Following that, you could equally go on and do some type checking - as long as valid numbers did not start with a 0 in which case is might be more difficult.
If you don't fail early, then go on with the regex solutions already posted.