include dot(.) and hyphen(-) in a regex

被刻印的时光 ゝ 提交于 2021-02-05 12:30:53

问题


 if(preg_match('/[^a-z\-0-9]/i', $value))

    {
    echo "<META HTTP-EQUIV='Refresh' Content='0; URL=http://$ponka/name/error'>";
}

how to include a dot and hyphen in the above code? I know how to add dot or hyphen in the code which is if-yes-then-if-then-else. This code is if-no-then-if-then-else (if you got what I am trying to say)


回答1:


The hyphen doesn't need to be escaped if it's the first or last in the character class.
The dot also doesn't need to escaped when used inside a character class [] i.e.:

/[^a-z.0-9-]/i

NOTES:

Apart from the above, the meta characters that also need to be escaped inside a character class are:

^ (negation)
- (range)
] (end of the class)
\ (escape char)



回答2:


The hyphen is already in there, simply add an escaped dot using \..

/edit: But as noted in the comment the escaping isn't needed.




回答3:


Assuming you are talking about the regex, you escape both with a slash \.

/[^a-z\.\-0-9]/i



回答4:


The hyphen does not need to be escaped if it is the last character in the Regex group. But the dot should always be escaped, so

'/[^a-z\.0-9-]/i'

Will check for a to z, . , 0 to 9 and - in that order, case insensitively.



来源:https://stackoverflow.com/questions/33131492/include-dot-and-hyphen-in-a-regex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!