How to Check if String Starts with Specific Character in PHP?

03-Apr-2023

.

Admin

How to Check if String Starts with Specific Character in PHP?

Hi Dev,

This tutorial will give you example of how to check if string starts with specific character in php?. This post will give you simple example of check if string starts with character to check if string starts with a specific character. I would like to share with you use php built-in function strpos(). We will look at example of provide the string and character as arguments to strpos().

There are example to php check if string starts with specific character in php. in this example, we will use to strpos() function to check if string starts with specific character in php. so let's the following example with output.

Example 1:


index.php

<?php

// Function to check string starting

$string = "Hello World";

$character = "H";

if (strpos($string, $character) === 0) {

echo "\"{$string}\" starts with specified character \"{$character}\".";

}

else {

echo "\"{$string}\" does not start with specified character \"{$character}\".";

}

?>

Output:

"Hello World" starts with specified character "H"

Example 2:

index.php

<?php

// Function to check string starting

$string = "Hello World";

$character = "B";

if (strpos($string, $character) === 0) {

echo "\"{$string}\" starts with specified character \"{$character}\".";

}

else {

echo "\"{$string}\" does not start with specified character \"{$character}\".";

}

?>

Output:

"Hello World" does not start with specified character "B"

I hope it could help you...

#PHP