str_starts_with
Checks whether a string starts with a given substring.
Available since: PHP 8.0
Syntax
str_starts_with(string $haystack, string $needle): boolParameters
| Parameter | Type | Description |
|---|---|---|
| $haystack | string | The string to check. |
| $needle | string | The expected beginning of the string. |
Return value
bool`true` if the string starts with the substring, `false` otherwise.
Examples
Checking the protocol of a URL:
<?php
var_dump(str_starts_with('https://example.com', 'https://'));
var_dump(str_starts_with('http://example.com', 'https://'));Output:
bool(true)
bool(false)The companion str_ends_with() checks the end of a string:
<?php
var_dump(str_ends_with('photo.png', '.png'));Output:
bool(true)Notes
The comparison is case-sensitive. Both functions were added in PHP 8.0; older code compared the result of substr() instead.
See also
- str_contains — Checks whether a string contains a given substring.
Related recipes
In the tutorial
- Strings — Working with strings in PHP — quotes, concatenation, length, searching, replacing and multibyte functions.