regex return false if string contains at least one questionmark
I have a string where i want to detect if it contains at least one question mark. if it does return false.开发者_StackOverflow I tried to look for it but questiomark seems is a special character. How would you go about it?
thank you.
You just need to escape the ? in your regex. preg_match('/\?/','A string?',$matches)
will return a match for ? if one exists.
That said, you could just use strpos()
for this. It would be faster since you don't really need a regex engine to find ?
No need for regex.
if (strpos($str, '?') !== false) {
return false;
}
// Shorter but always executes due to lack of a conditional structure
// May not be what you need if you're doing various other checks
return strpos($str, '?') === false;
But you're right, ?
is a special character in regex. It tells the regex engine to look for zero or one occurrence of something.
If you're involving a check for a question mark in a more complicated regex, then as Paul Kehrer says you simply escape it with a backslash.
精彩评论