PHP Snippets

Check If String Starts With Another String

Andrei Surdu Andrei Surdu ·

This function checks if a given string starts with another string. It also uses strpos but checks specifically if the substring’s position is 0, meaning it’s at the beginning of the string. This function is useful for checking if a string follows a certain format or pattern that starts with a specific sequence of characters.

PHP Function:

function startsWith($str, $substr) { return strpos($str, $substr) === 0; }

// Example
echo startsWith('Hello, World!', 'Hello'); // true
echo startsWith('Hello, World!', 'World'); // false

Comments

Share your thoughts and join the conversation

Loading comments...

Leave a Comment

Your email will not be published

Comments are moderated and will appear after approval

0/2000