I'm currently working on a PHP script, and i need to check a string. If the string contains other characters than 0 1 and spaces, then i would like to return an error. If the string only contains 0 1 and spaces then continue with the code.
我目前正在研究PHP脚本,我需要检查一个字符串。如果字符串包含除0 1和空格之外的其他字符,那么我想返回错误。如果字符串仅包含0 1和空格,则继续使用代码。
The string is user submitted, and therefore it can be very long.
该字符串是用户提交的,因此可能很长。
I have tried searching the web for a solution, but i cant find exactly what i am looking for.
我曾尝试在网上搜索解决方案,但我无法找到我正在寻找的内容。
But i have a feeling that i am going to use regex to solve my problem. I have found the following code:
但我有一种感觉,我将使用正则表达式来解决我的问题。我找到了以下代码:
if(preg_match('/^[0-1]$/', $txt_string) == 1) {
return "Ok";
} else {
return "Error";
}
But the problem here is that it seems to fail when i insert more than one number.
但问题是,当我插入多个数字时似乎失败了。
/Morten.
/莫滕。
1 个解决方案
#1
3
You forgot the quantifier, and [0-1]
is effectively equivalent to [01]
. Also, it seems like you forgot to include spaces in your character class. You can add it, if you want them to match.
你忘记了量词,[0-1]实际上相当于[01]。此外,您似乎忘记在角色类中包含空格。如果您希望它们匹配,您可以添加它。
So, your regex should be:
所以,你的正则表达式应该是:
'/^[01 ]+$/'
#1
3
You forgot the quantifier, and [0-1]
is effectively equivalent to [01]
. Also, it seems like you forgot to include spaces in your character class. You can add it, if you want them to match.
你忘记了量词,[0-1]实际上相当于[01]。此外,您似乎忘记在角色类中包含空格。如果您希望它们匹配,您可以添加它。
So, your regex should be:
所以,你的正则表达式应该是:
'/^[01 ]+$/'