我需要在PHP中创建一个函数,当有人提交一个按钮时,如果字符串与生成的随机数一起出现,它将检查。 字符串将始终相同,但字符串内的数字将始终不同。
示例字符串:
如果在提交按钮后显示此字符串,我需要编写测试。检查数字的正则表达式应该如何?
if(buttonSubmitted()){
if($currentString == "Heloo !probablySomeRegex! how are you?"){
return TRUE
}else{
return FALSE;
}
如果您需要任何其他信息,请告诉我,我会提供。提前谢谢
答案 0 :(得分:2)
尝试以下代码
if(buttonSubmitted()){
if(preg_match('/^Heloo \d+ how are you\?$/', $currentString)){
return TRUE
}else{
return FALSE;
}
}
修改强> 它区分大小写。它会检查“Heloo”之后的任何数字组合然后“你好吗?”
答案 1 :(得分:1)
您可以使用以下内容:
if (preg_match('/Heloo \d+ how are you\?/im', $subject)) {
return TRUE;
} else {
return FALSE;
}
正则表达式说明:
Heloo \d+ how are you\?/mi
Heloo matches the characters Heloo literally (case insensitive)
\d+ match a digit [0-9]
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
how are you matches the characters how are you literally (case insensitive)
\? matches the character ? literally
m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
答案 2 :(得分:1)
我倾向于远离正则表达式,但如果我要自己做这个方法,我就这样做。
// If you know that the string is going to be the same structure.
function getNumberInString($string) {
return explode(' ', $string)[1];
}
// If you don't know where the number will occur in the string.
function getNumberInString($string) {
// Loops each piece of the sentence and returns the number if there is a number.
foreach (explode(' ', $string) as $piece) {
if (is_numeric($piece) ) return $piece;
}
return false;
}
希望这会有所帮助:) 这个答案应该做你想要的,因为每次字符串完全相同,第一个将快速,轻松地帮助。