Use PHP Strpos() to Check if a String Starts with

Posted on April 7, 2019 at 11:09 am

Check if a string starts with a specific word in PHP with strpos():

$string = "Hello World!";
 
$findme = "Hello";
 
if(strpos($string, $findme) !== false && strpos($string, $findme) === 0)
{
    echo "String found at pos 0";
}
else
{
    echo "String not found at pos 0";
}

Strpos() can return 0 (position) which is equivalent to false in PHP.

So first we check if strpos() !== false and then if it returns 0 (position).

Receive updates via email

Other Posts

Updated Posts