PHP Reference ยท String Functions
PHP str_starts_with() function
Reference for PHP str_starts_with(): test whether a string begins with a given prefix, case sensitivity, the empty prefix rule and pre-8.0 alternatives.
str_starts_with() returns true when a string begins with the given prefix and false otherwise. It was added in PHP 8.0 and replaces older tricks such as substr($s, 0, 3) === "abc" or strpos($s, "abc") === 0.
The comparison is case-sensitive and byte-based. An empty prefix always matches, so str_starts_with("abc", "") is true.
<?php var_dump(str_starts_with("https://example.com", "https://")); // bool(true) var_dump(str_starts_with("Hello", "hello")); // bool(false)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
str_starts_with(string $haystack, string $needle): bool
| Name | Description |
|---|---|
$haystack |
The string to check. |
$needle |
The prefix to look for. An empty string always matches. |
Return value: true if $haystack starts with $needle, otherwise false.
Errors: a TypeError is thrown for values that cannot be converted to a string, such as arrays. Under declare(strict_types=1), non-string scalars are rejected too.
Usage notes
- Case-sensitive. Lower-case both sides first for a case-insensitive test (use
mb_strtolower()for non-ASCII text). - Empty prefix is always found. Guard against an empty
$needleyourself if that would be a bug in your code. - Longer needle than haystack simply returns
false. - Not a regular expression. Characters such as
.or^are literal. - Added in PHP 8.0. For older code,
strncmp($s, $prefix, strlen($prefix)) === 0is the efficient equivalent; avoidstrpos(...) === 0on long strings because it searches the whole string when the prefix is missing. - Removing the prefix needs a separate
substr()call, as the second example shows. - Companions.
str_ends_with()checks the end andstr_contains()checks anywhere.
Related
str_ends_with(),str_contains(),strpos(),substr()- Lessons: Strings, String functions