如何在 PHP if 语句中编写正则表达式


how to write a regular expression in PHP if statment

我正在用PHP编写一个聊天机器人。

这是代码的一部分

public function messageReceived($from, $message){
        $message = trim($message);
                if(stristr($message,"hi")|| stristr($message,"heylo")||stristr($message,"hello")||stristr($message,"yo")||stristr($message,"bonjour")){
            return "Hello,$from,how are you"; // help section
        }

现在在 if 语句中,我可以使用正则表达式,这样如果消息以 :H 或 Y 它将返回给定的语句。

某种东西:

H* ||正式语文中的Y*

有没有这样的方法可以做到这一点?

if(preg_match('/^(?:hi|hey|hello) (.+)/i', $str, $matches)) {
    echo 'Hello ' . $matches[1];
}

解释:

/ # beginning delimiter
  ^ # match only at the beginning of the string
  ( # new group
    ?: # do not capture the group contents
    hi|hey|hello # match one of the strings
  )
  ( # new group
    . # any character
      + # 1..n times
    )
/ # ending delimiter
  i # flag: case insensitive

您可以使用以下命令在消息开头检查 HY(不区分大小写)

preg_match('/^H|Y/i', $message)

您可以使用preg_match来实现此目的:

if (preg_match('/^(H|Y).*/', $message)) {
    // ...

你可以得到第一个字母和$message[0]

由于您确定要比较第一个字母,因此可以在不使用正则表达式的情况下执行此操作。

    if( substr($message, 0, 1) =='H' || substr($message, 0, 1) == 'Y' ){
        //do something
    }

您的整个函数将如下所示:

public function messageReceived($from, $message){
  $message = trim($message);
  if(preg_match('/^H|Y/i', $message){
     return "Hello $from, how are you"; // help section
  }
  else {
     // check for other conditions
  }
}