Manikandan
Manikandan

Reputation: 512

How to match only the first letter of the string

I want to match only the first letter of the string i.e 'bot'. For ex: It should run a function if user types "bot hi" and should not work if they type "hi bot there"

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

the above code works even if I type "hi bot there"

Upvotes: 0

Views: 946

Answers (2)

ScaisEdge
ScaisEdge

Reputation: 133400

You should use the ^ for tell at begin of the string

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

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

Upvotes: 1

Ambrish Pathak
Ambrish Pathak

Reputation: 3968

You can check this with strpos() :

    $str = "bot hi";
    if (0 === strpos($str, 'bot')) {
       echo("str starts with bot");
   else{
       echo("str does not starts with bot");
       }
    }

Upvotes: 0

Related Questions