PASSWORD RESET

Your destination for complete Tech news

PHP

How to check if a string starts with a specific string in PHP?

494 0
< 1 min read

To check if a string starts with a specific string in PHP, you can use the strpos function. This function searches for a string within another string and returns the position of the first occurrence.

Here’s an example of how you can use it:

PHP 8 and newer

str_starts_with('Hello World', 'hello')

For PHP 7 and older

$str = 'Hello world';
if (strpos($str, 'Hello') === 0) {
    // String starts with "Hello"
} else {
    // String does not start with "Hello"
}

In this example, the strpos function searches for the string “Hello” within the string $str. If the position returned is 0 (the first character), it means that the string starts with “Hello”.

Note that the strpos function is case-sensitive, so “hello” and “Hello” are considered different strings. If you want to perform a case-insensitive search, you can use the stripos function instead.

$str = 'Hello world';
if (stripos($str, 'hello') === 0) {
    // String starts with "hello" (case-insensitive)
} else {
    // String does not start with "hello"
}

Another option is to use the substr function to compare the first characters of the string:

$str = 'Hello world';
if (substr($str, 0, 5) === 'Hello') {
    // String starts with "Hello"
} else {
    // String does not start with "Hello"
}

This method is faster than strpos and is also case-sensitive. If you need a case-insensitive comparison, you can use the strtolower function to lowercase both strings before comparing them.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.