Regular expression to check for two characters
I want to check if the value is 'H' or 'T' or else it can be 'H' orelse it can be 'T' or both 'H' and 'T'
this all is stored in an array
I'm using this regular expression to check these two words.
$combo = preg_match('[HT]',strtoupper($_REQUEST['combo']));
it gives me success if the value is HT . If i put just 'H' or 'T'...or recurring 'H' or 'T' it doesn't satisfy the code above.
hope this might help you understand...a simple coin toss game which has two possible out comes 'H'- heads and 'T'-tails.....User can play 9 rounds in all... $combo is storing this combination which contains H and T only...I'm checking a php call here from url that I got eg:- www.domain-name.com/submit_combo_predisc.php/?prefix=p&uid=username&txn=9574621083&combo=HHH&k=29c3550e430723e5c61a66bd03ba4ff5....
here user has got three inputs right and he wins certain amount for getting three combination right.in the url if I enter 'HH4' instead of 'HHH' it still displays u 开发者_Go百科got three combo right and the user is given certain amount for getting the three combinations right....which is actually wrong....because the value passed are 'HH4'...n not 'HHH'. User can actually misuse the url to win unlimited amount....
$combo = preg_match('/^(H|T|HT)$/',strtoupper($_REQUEST['combo']));
this matches H, T and HT.
if you want to match TH too,
$combo = preg_match('/^[HT]{1,2}$/',strtoupper($_REQUEST['combo']));
is the better choice.
the regex must be
'^[HT]{1,2}$'
This allows following values: 'H', 'T', 'HT', 'TH', 'HH' and 'TT' but nothing else!
$combo = preg_match('/[HhTt]/',$_REQUEST['combo']);
You want to use a quantifier for that. {1,2}
would work:
preg_match('/^[HT]{1,2}$/'
Note that your regex was also lacking delimiters. That's why it only ever matched HT
- because the square brackets were interpreted as delimiters rather than as character group.
Seems what you actually want (but never said) was to count the number of H
s and T
s. Then the simpler approach would be:
$combo = strlen(preg_replace('/[^HT]/i', "", $_REQUEST['combo']));
精彩评论