比较包含随机数的字符串


Compare strings which contains random number

我需要在PHP中创建一个函数,当有人提交按钮时,该函数将检查是否存在带有生成的随机数的字符串。字符串将始终相同,但字符串中的数字将始终不同。

字符串示例:

  • 你好吗
  • 你好吗
  • 你好吗
  • 你好吗

如果这个字符串在按钮提交后显示,我需要写一个测试。我用于检查数字的正则表达式应该是什么样子?

if(buttonSubmitted()){
    if($currentString == "Heloo !probablySomeRegex! how are you?"){
        return TRUE
    }else{
        return FALSE;
    }

如果你需要任何额外的信息,请告诉我,我会提供。提前感谢

尝试以下代码

if(buttonSubmitted()){
    if(preg_match('/^Heloo 'd+ how are you'?$/', $currentString)){
        return TRUE
    }else{
        return FALSE;
    }
}

编辑:它区分大小写。在那之后,它将检查"Heloo"的任何数字组合,然后检查"你好吗?"

您可以使用以下内容

if (preg_match('/Heloo 'd+ how are you'?/im', $subject)) {
    return TRUE;
} else {
    return FALSE;
}

Regex101演示


Regex解释:

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])

我倾向于远离Regex,但如果我要制定自己的方法,我会这样做。

// 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;
}

希望这能有所帮助:)这个答案应该是你想要的,因为每次字符串都是完全相同的,第一个答案将快速而容易地提供帮助。