如何只匹配字符串的第一个字母

时间:2017-02-04 12:35:55

标签: php

我想只匹配字符串的第一个字母,即机器人&#39;。 例如: 如果用户键入<?php mysql_select_db("$database"); $sql = "select test, rate FROM product"; $result = mysql_query($sql) or die(mysql_error()); while($row = mysql_fetch_assoc($result)) { echo <<<EOL <input type="checkbox" name="name[]" value="{$row['test']}-{$row['rate']}" /> {$row['test']}-{$row['rate']}<br /> EOL; } ?> ,它应该运行一个函数,如果键入"bot hi"

则不应该运行
"hi bot there"

即使我输入if(preg_match('[bot ]', strtolower($message))) { $msg = str_replace('bot ', '', $message); //Some message response }

,上述代码也能正常运行

2 个答案:

答案 0 :(得分:1)

你应该在字符串的开头使用^ for tell

  if ( preg_match("/^bot (.*)/i", $message) ) {

   $msg = str_replace('bot ', '', $message);
    //Some message response
 }

答案 1 :(得分:0)

您可以使用strpos()

进行检查
    $str = "bot hi";
    if (0 === strpos($str, 'bot')) {
       echo("str starts with bot");
   else{
       echo("str does not starts with bot");
       }
    }
相关问题