[英]How can I Accept only letter, number, comma (,) and dot (.) using php
I want to accept only letter, number, comma and dot using following regular expression. 我想使用以下正则表达式只接受字母,数字,逗号和点。 If i use
$string
it's saying invalid data but If i use $string2
it's saying valid data. 如果我使用
$string
它会说无效数据但是如果我使用$string2
它就是说有效数据。
1) Why $string
is not accepting as valid data ? 1)为什么
$string
不接受有效数据? anything I'm missing ? 我错过了什么?
2) If i accept comma then how can I escape it ? 2)如果我接受逗号,我怎么能逃脱它? Using mysqli_real_escape_string ?
使用mysqli_real_escape_string? If so then it's showing backslash when I showing it from Db.
如果是这样的话,当我从Db显示它时它会显示反斜杠。 Please help.
请帮忙。 Thank You.
谢谢。
$string = "I m a good boy";
$string2 = "Imagoodboy";
if(preg_match("/^[a-zA-Z0-9]+$/", $string) == 0)
echo "Invalid data";
else
echo "Valid data";
You need to include .
你需要包括
.
in your character class and reverse your if condition checks: 在你的角色类中并反转你的if条件检查:
if(preg_match('/^[a-zA-Z0-9.]+$/', $string))
echo "valid data";
else
echo "InValid data";
Also $string
has spaces also and space is not in your allowed character list that's why it is failing. $string
也有空格,空间不在你允许的字符列表中,这就是它失败的原因。 If you want to include spaces also make regex as: 如果你想包含空格也使正则表达式为:
/^[a-zA-Z0-9. ]+$/
First String contain whitespace. First String包含空格。 According to your regular expression space is not valid.To validate $string you have to make valid whitespace in your regular expression.
根据你的正则表达式,空间无效。要验证$ string,你必须在正则表达式中创建有效的空格。
Try this : 尝试这个 :
preg_match("/[^a-zA-Z0-9., ]/",$string);
^
Space
You missed a space and .
你错过了一个空间
.
, try it: , 试试吧:
if(preg_match("/^[\d\w\s\.]+$/", $string) == 0)
echo "Invalid data";
else
echo "Valid data";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.