Backend Development 3 min read

Using PHP 8.1 str_starts_with() Function: Syntax, Examples, and Case Sensitivity

PHP 8.1 introduces the str_starts_with() function, which checks if a string begins with a given substring, returning true or false; this article explains its syntax, demonstrates basic and URL-check examples, highlights case‑sensitivity, and mentions the case‑insensitive variant str_starts_with_ci().

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP 8.1 str_starts_with() Function: Syntax, Examples, and Case Sensitivity

In PHP programming, checking whether a string starts with a specific substring is common. PHP 8.1 adds the str_starts_with() function to simplify this task.

The function takes two parameters—the haystack (main string) and the needle (substring)—and returns true if the haystack begins with the needle, otherwise false .

str_starts_with() function basic syntax:

<code>bool str_starts_with ( string $haystack , string $needle )</code>

Here $haystack is the main string and $needle is the substring to check.

str_starts_with() function examples:

<code>$mainStr = "Hello, World!";
$subStr  = "Hello";

if (str_starts_with($mainStr, $subStr)) {
    echo "主串以子串开头";
} else {
    echo "主串不以子串开头";
}
</code>

This code outputs “主串以子串开头” because “Hello, World!” starts with “Hello”.

The function can also be used to verify a URL’s protocol. Example:

<code>$url      = "https://www.example.com";
$protocol = "https";

if (str_starts_with($url, $protocol)) {
    echo "URL使用https协议";
} else {
    echo "URL不使用https协议";
}
</code>

The above prints “URL使用https协议” since the URL begins with “https”.

Note that str_starts_with() is case‑sensitive. For case‑insensitive checks, PHP provides the str_starts_with_ci() variant.

Overall, str_starts_with() offers a concise way to determine string prefixes, useful for tasks such as URL protocol validation and general substring checks.

Additional learning resources are listed, including tutorials on Vue3, Laravel, Swoole, and Workerman.

backend-developmentPHPTutorialstring-functionsPHP8
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.