PHP example

How to check if a string starts with another string in PHP

8 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Use str_starts_with($haystack, $needle) and str_ends_with($haystack, $needle) (PHP 8.0 and later). Both return true or false and are case-sensitive. To ignore case, use strncasecmp($haystack, $needle, strlen($needle)) === 0. On PHP 7, use strncmp the same way, never strpos($haystack, $needle) == 0.

Until PHP 8.0 there was no built-in "starts with" or "ends with", so every codebase grew its own startsWith helper, and many of them were built on strpos, substr or ltrim in ways that break on edge cases. The sections below cover str_starts_with and str_ends_with, case-insensitive and UTF-8 checks, correct helpers for PHP 7, the strpos trap, checking a list of prefixes or file extensions, and removing a prefix once you have found it, then a table to pick from. To find text anywhere in a string instead, see how to check if a string contains a substring. Each example runs on this page: hit Run, then edit the code and run it again.

1str_starts_with and str_ends_with (PHP 8.0+)Recommended

Both functions take the string to check (the haystack) and the prefix or suffix (the needle) and return a bool. They compare bytes exactly, so case matters, and they only look at the start or the end: they never search the rest of the string. A needle longer than the haystack is simply false, with no warning.

starts_with.php
<?php

$file = 'report-2026.csv';

var_dump(str_starts_with($file, 'report'));
var_dump(str_ends_with($file, '.csv'));
var_dump(str_starts_with($file, 'Report'));   // case-sensitive
var_dump(str_ends_with($file, '.CSV'));

$url = 'https://example.com/docs';
if (str_starts_with($url, 'https://')) {
    echo "Secure URL\n";
}

// A needle longer than the string is simply false
var_dump(str_starts_with('csv', 'csv-export'));

// An empty prefix or suffix always matches
var_dump(str_starts_with($file, ''));
var_dump(str_ends_with('', ''));

Output

'report' and '.csv' match, while 'Report' and '.CSV' print bool(false) because of the capital letters. The last two lines print bool(true): every string starts and ends with the empty string, even an empty one, so check $needle !== '' yourself if the needle comes from user input. On PHP 7, use the helpers in section 3 or the symfony/polyfill-php80 package, which defines both functions when they are missing.

2Ignoring case: strncasecmp and substr_compare

There is no str_istarts_with. For a case-insensitive prefix, compare only the first strlen($needle) bytes with strncasecmp, which returns 0 when they are equal. For a suffix, substr_compare takes a negative offset (count from the end) and a fifth argument that turns on case-insensitive comparison. Both fold only the ASCII letters A to Z, so for accented text lowercase both sides with mb_strtolower and use str_starts_with.

ignore_case.php
<?php

$header = 'Content-Type: text/html';

// strncasecmp compares the first n bytes and ignores case; 0 means equal
var_dump(strncasecmp($header, 'content-type:', 13) === 0);

// substr_compare ignores case when its fifth argument is true
$photo = 'IMG_2041.JPG';
var_dump(substr_compare($photo, 'img_', 0, 4, true) === 0);
var_dump(substr_compare($photo, '.jpg', -4, 4, true) === 0);

// stripos() === 0 also works, but searches the whole string on a miss
var_dump(stripos($photo, 'img') === 0);

function startsWithIgnoreCase(string $haystack, string $needle): bool
{
    return strncasecmp($haystack, $needle, strlen($needle)) === 0;
}

function endsWithIgnoreCase(string $haystack, string $needle): bool
{
    $length = strlen($needle);
    return $length === 0
        || substr_compare($haystack, $needle, -$length, $length, true) === 0;
}

var_dump(startsWithIgnoreCase('README.md', 'readme'));
var_dump(endsWithIgnoreCase('README.md', '.MD'));
var_dump(endsWithIgnoreCase('md', 'README.md'));

// Outside ASCII these only fold A-Z: lowercase with mb_strtolower
$word = 'Éclair';
var_dump(startsWithIgnoreCase($word, 'éc'));
var_dump(str_starts_with(mb_strtolower($word), mb_strtolower('ÉC')));

// An exact, case-sensitive check is byte-safe for UTF-8 as it is
var_dump(str_starts_with($word, 'Éc'));

Output

The first six checks all print bool(true), and endsWithIgnoreCase('md', 'README.md') is correctly bool(false) when the needle is longer than the string. With 'Éclair', strncasecmp gives bool(false) for 'éc' because É and é are different bytes in UTF-8 and it only knows A to Z; mb_strtolower on both sides fixes that. You only need the mb_ functions to ignore case: an exact prefix such as 'Éc' is the same bytes at the start of the string, so str_starts_with handles UTF-8 correctly as it is. stripos(...) === 0 gives the right answer too, but when the prefix is not there it keeps looking through the whole string first (section 4 shows the cost).

3Before PHP 8.0: strncmp and substr_compare

If your host still runs PHP 7, write the two helpers yourself. strncmp compares only the first strlen($needle) bytes, so it checks the start without copying anything. substr_compare with a negative offset compares the end. substr($haystack, 0, $n) === $needle works and reads well, but it builds a new string on every call. The one edge case to handle by hand is the empty needle.

before_php8.php
<?php

// Before PHP 8.0: strncmp for the start, substr_compare for the end
function startsWith(string $haystack, string $needle): bool
{
    return strncmp($haystack, $needle, strlen($needle)) === 0;
}

function endsWith(string $haystack, string $needle): bool
{
    return $needle === ''
        || substr_compare($haystack, $needle, -strlen($needle)) === 0;
}

$path = '/admin/users';

var_dump(startsWith($path, '/admin'));
var_dump(endsWith($path, 'users'));
var_dump(endsWith('rs', 'users'));   // needle longer than haystack

// substr() === reads well, but copies part of the string first
var_dump(substr($path, 0, strlen('/admin')) === '/admin');
var_dump(substr($path, -strlen('users')) === 'users');

// Why endsWith() checks for '': -strlen('') is 0, the whole string
var_dump(substr($path, -strlen('')) === '');
var_dump(substr_compare($path, '', -strlen('')) === 0);
var_dump(endsWith($path, ''));

Output

The helpers give bool(true) for '/admin' and 'users', and bool(false) when the suffix is longer than the string. The last three lines show the empty-needle bug that many copied endsWith functions have: -strlen('') is 0, so substr and substr_compare look at the whole string and print bool(false), while str_ends_with says true. The $needle === '' guard makes the helper agree with PHP 8. startsWith needs no guard, since strncmp with a length of 0 returns 0.

4The strpos == 0 trap and its cost

The most common old answer is strpos($haystack, $needle) === 0: find the first match and check that it is at position 0. It works with three equals signs, and fails with two. strpos returns false when there is no match, and in PHP false == 0 is true, so the loose version says every string starts with a prefix it does not contain. Even the strict version does extra work: on a miss, strpos searches all the way to the end before it can answer.

strpos_trap.php
<?php

$path = '/admin/users';

// strpos returns the position: 0 at the start, false when missing
var_dump(strpos($path, '/admin'));
var_dump(strpos($path, '/blog'));

// Bug: false == 0 is true, so a missing prefix "matches"
var_dump(strpos($path, '/blog') == 0);

// Correct, with ===
var_dump(strpos($path, '/admin') === 0);
var_dump(strpos($path, '/blog') === 0);

// The cost: on a miss, strpos keeps searching to the end
$log = str_repeat('.', 1_000_000) . 'ERROR';
var_dump(strpos($log, 'ERROR'));
var_dump(strpos($log, 'ERROR') === 0);
var_dump(str_starts_with($log, 'ERROR'));

Output

strpos returns int(0) for '/admin' and bool(false) for '/blog', and the loose == 0 turns that false into bool(true): a path that does not start with /blog passes the check. With === the answers are right. The last three lines show the cost: to answer bool(false), strpos walked a million characters and found ERROR at int(1000000), while str_starts_with compared five bytes. stripos(...) === 0 has the same cost.

5Checking several prefixes or suffixes

File extensions and URL schemes are the usual case: does the name end with any of .jpg, .png or .gif? PHP 8.4 added array_any, which stops at the first match, and array_find, which returns the element that matched. Lowercase the string once before the check when the list should ignore case. On older versions, a foreach that returns on the first hit does the same.

several.php
<?php

$files = ['photo.JPG', 'notes.txt', 'logo.png', 'backup.tar.gz'];
$images = ['.jpg', '.jpeg', '.png', '.gif'];

// PHP 8.4: array_any stops at the first suffix that matches
foreach ($files as $file) {
    $lower = strtolower($file);
    $isImage = array_any(
        $images,
        fn(string $ext): bool => str_ends_with($lower, $ext)
    );
    printf("%-14s %s\n", $file, $isImage ? 'image' : 'other');
}

// A suffix can span dots; pathinfo() only sees the last one
var_dump(str_ends_with('backup.tar.gz', '.tar.gz'));
echo pathinfo('backup.tar.gz', PATHINFO_EXTENSION), "\n";

// array_find (PHP 8.4) returns the prefix that matched, or null
$schemes = ['https://', 'http://', 'ftp://'];
$urls = ['https://example.com', 'ftp://files.example.com', 'ssh://host'];
foreach ($urls as $url) {
    $scheme = array_find(
        $schemes,
        fn(string $s): bool => str_starts_with($url, $s)
    );
    echo $url, ' => ', $scheme ?? 'none', "\n";
}

// Before PHP 8.4: a loop that returns on the first match
function startsWithAny(string $haystack, array $prefixes): bool
{
    foreach ($prefixes as $prefix) {
        if (str_starts_with($haystack, $prefix)) {
            return true;
        }
    }
    return false;
}

var_dump(startsWithAny('http://example.com', $schemes));
var_dump(startsWithAny('//example.com', $schemes));

Output

Because the name is lowercased first, photo.JPG counts as an image. str_ends_with can check a two-part suffix such as .tar.gz, while pathinfo reports only gz. array_find returns the scheme itself, or null for ssh://host, so ?? prints none. The extension check only looks at the name: it does not prove the file is an image, so check the content too before trusting an upload.

6Removing a known prefix or suffix

Often you check for a prefix so you can strip it. Do the check, then cut exactly strlen($prefix) bytes with substr. Two shortcuts look right and are not: ltrim and rtrim treat their second argument as a set of characters to strip, not a string, and str_replace removes every occurrence, not only the one at the start.

remove_prefix.php
<?php

function removePrefix(string $text, string $prefix): string
{
    return str_starts_with($text, $prefix)
        ? substr($text, strlen($prefix))
        : $text;
}

function removeSuffix(string $text, string $suffix): string
{
    return $suffix !== '' && str_ends_with($text, $suffix)
        ? substr($text, 0, -strlen($suffix))
        : $text;
}

echo removePrefix('https://hello.example', 'https://'), "\n";
echo removePrefix('http://hello.example', 'https://'), "\n";
echo removeSuffix('budget.txt', '.txt'), "\n";
echo removeSuffix('budget.txt', ''), "\n";

// Wrong: ltrim and rtrim take a list of characters, not a string
echo ltrim('https://hello.example', 'https://'), "\n";
echo rtrim('budget.txt', '.txt'), "\n";

// Wrong: str_replace removes every occurrence, not just the prefix
$link = 'https://a.example/?next=https://b.example';
echo str_replace('https://', '', $link), "\n";
echo removePrefix($link, 'https://'), "\n";

Output

The helpers turn https://hello.example into hello.example, leave the http:// link alone, and turn budget.txt into budget. The $suffix !== '' guard matters: substr($text, 0, -0) would return an empty string. ltrim with 'https://' strips any of the characters h, t, p, s, : and /, so it eats the h of hello and prints ello.example; rtrim with '.txt' also takes the t of budget and prints budge. str_replace drops the second https:// inside the query string as well, while removePrefix touches only the start.

7Which should you use?

MethodChecksCaseBest for
str_starts_with($h, $n)StartSensitiveMost prefix checks on PHP 8.0+
str_ends_with($h, $n)EndSensitiveMost suffix checks on PHP 8.0+
strncasecmp($h, $n, strlen($n)) === 0StartIgnores ASCII caseCase-insensitive prefix
substr_compare($h, $n, -$len, $len, true) === 0EndIgnores ASCII caseCase-insensitive suffix
str_starts_with(mb_strtolower($h), ...)StartIgnores Unicode caseCase-insensitive UTF-8 text
strncmp($h, $n, strlen($n)) === 0StartSensitivePHP 7 and older
strpos($h, $n) === 0StartSensitiveAvoid: scans on a miss; == 0 is a bug
array_any($list, fn ...)EitherDepends on callbackSeveral prefixes or extensions (8.4+)

Frequently asked questions

How do I use str_starts_with and str_ends_with on PHP 7?

Both were added in PHP 8.0. On PHP 7, use strncmp($haystack, $needle, strlen($needle)) === 0 for the start and $needle === '' || substr_compare($haystack, $needle, -strlen($needle)) === 0 for the end, or install symfony/polyfill-php80, which defines both functions when they are missing. If you declare your own global str_starts_with, wrap it in if (!function_exists('str_starts_with')) so the code keeps working after the host upgrades.

Is there a case-insensitive str_starts_with in PHP?

No. For ASCII text use strncasecmp($haystack, $needle, strlen($needle)) === 0 for a prefix and substr_compare($haystack, $needle, -strlen($needle), strlen($needle), true) === 0 for a suffix. For accented or other UTF-8 text, lowercase both sides with mb_strtolower and call str_starts_with. mb_convert_case($s, MB_CASE_FOLD) goes one step further and folds ß to ss, so STRASSE starts with straße.

Why does str_starts_with return true for an empty string?

Every string starts and ends with the empty string, so str_starts_with($text, '') and str_ends_with($text, '') are always true, even when $text is empty too. If the prefix comes from user input or config, check $needle !== '' first. Older hand-written endsWith helpers built on substr($h, -strlen($n)) get this case wrong and return false.

Why is strpos($string, $prefix) == 0 wrong?

strpos returns false when the prefix is not found, and false == 0 is true in PHP, so the loose check says yes for strings that do not contain the prefix at all. strpos(...) === 0 is correct but searches the whole string on a miss. Use str_starts_with on PHP 8.0 and later, or strncmp on older versions.

Why does ltrim remove more than the prefix?

The second argument of ltrim and rtrim is a list of characters, not a string. ltrim('https://hello.example', 'https://') strips every leading h, t, p, s, colon and slash, which gives ello.example. To remove an exact prefix, check it with str_starts_with and cut it with substr($text, strlen($prefix)).

How do I check a file extension in PHP?

Lowercase the name and use str_ends_with(strtolower($name), '.png'), or array_any with a list of extensions on PHP 8.4 and later. pathinfo($name, PATHINFO_EXTENSION) returns only the part after the last dot, so it gives gz for backup.tar.gz. With a regex, anchor with \z rather than $: preg_match('/\.png$/', "logo.png\n") returns 1 because $ also matches before a final newline, while \z returns 0.

Why do I get "Passing null to parameter #1 ($haystack) of type string is deprecated"?

Since PHP 8.1, passing null to a string parameter of a built-in function prints a deprecation, for example Deprecated: str_starts_with(): Passing null to parameter #1 ($haystack) of type string is deprecated. The function still returns false, but the message means a value you expected to be a string is missing. Fix the source, or default it: str_starts_with($name ?? '', $prefix).

Run it yourself

Open any of these in the full PHP editor to tweak, run and share.

PHP playground