I have my variable $_GET['artist']
and I'd like to check:
one
letter, and this letter is from a
to z
(case sensitive, so A
is not valid);all
or other
How can I check it with regex
and preg_match()
on PHP?
if (preg_match('/^([a-z]|all|other)$/', $_GET['artist']) === 1) {
// True
}
Assuming all
and other
should also be case sensitive.
function check($str){
$c=strlen($str)==1 ? ord($str) : 0; // get the ascii code if it is a single character
return ($c>=ord('a') && $c<=ord('z')) // it is a single character between a and z
|| strpos($str,'all')!==false // it contains "all"
|| strpos($str,'other')!==false; // it contains "other"
}
check($_GET['artist']);
See, no regex.
Edit: To humor our esteemed moderator, here goes the comments.
Edit 2: I wrote a little profile for both solutions, and here are the results:
Test PHP RegExp
a 0.11241698265076 0.16329884529114
other 0.15441918373108 0.17051410675049
all 0.11415100097656 0.16919803619385
al 0.14953303337097 0.16402912139893
// tested over 100k iterations (less TTC is better)
One can see who's the best when it comes to speed. Though I would personally opt for this one, there are certainly reasons why a regular expression would favorable. The facts are in place, and I just can't be bothered with this pointless argument.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.