简体   繁体   English

正则表达式检查两个字符

[英]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' 我想检查值是'H'还是'T',否则它可能是'H',它可以是'T'或'H'和'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 . 如果值为HT,它会给我成功。 If i put just 'H' or 'T'...or recurring 'H' or 'T' it doesn't satisfy the code above. 如果我只是'H'或'T'......或反复出现'H'或'T',它就不符合上述代码。

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=HH‌​H&k=29c3550e430723e5c61a66bd03ba4ff5.... 希望这可以帮助你理解...一个简单的投币游戏有两个可能的'H' - 头和'T'尾...用户可以玩9轮所有... $组合存储这个组合只包含H和T ......我在这里检查一个来自url的php调用,例如: - www.domain-name.com/submit_combo_predisc.php/?prefix=p&uid=username&txn=9574621083&combo=HH H&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 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'. 这里用户有三个输入正确,他赢得一定数量的三个组合权。如果我输入'HH4'而不是'HHH',它仍然显示你有三个组合权利,用户有一定数量获得正确的三种组合....这实际上是错误的....因为传递的值是'HH4'...... n不是'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. 这匹配H,T和HT。

if you want to match TH too, 如果你想匹配TH,

$combo  = preg_match('/^[HT]{1,2}$/',strtoupper($_REQUEST['combo']));

is the better choice. 是更好的选择。

You want to use a quantifier for that. 你想使用量词。 {1,2} would work: {1,2}可行:

 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. 这就是为什么它只与HT匹配 - 因为方括号被解释为分隔符而不是字符组。


Seems what you actually want (but never said) was to count the number of H s and T s. 似乎你真正想要的(但从未说过)是计算H s和T s的数量。 Then the simpler approach would be: 那么更简单的方法是:

 $combo = strlen(preg_replace('/[^HT]/i', "", $_REQUEST['combo']));

the regex must be 正则表达式必须是

'^[HT]{1,2}$'

This allows following values: 'H', 'T', 'HT', 'TH', 'HH' and 'TT' but nothing else! 这允许以下值:'H','T','HT','TH','HH'和'TT',但没有别的!

$combo  = preg_match('/[HhTt]/',$_REQUEST['combo']); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM