PHP check if string ends with substring
May 14, 2022 ‐ 2 min read
Do you need to find out whether a PHP string ends with a certain substring?
Checking whether a PHP string ends with a certain substring can be as easy as calling str_ends_with()
or somewhat more complex logic using substr_compare()
depending on your PHP version.
For PHP 8
PHP 8.0 introduced the new str_ends_with()
function which is perfect for this use-case. It works just as expected, first you pass the string you wish to inspect and second the substring you are looking for. If the substring is present then the result will be true
, otherwise it will be false
.
<?php // PHP 8+
$result = str_ends_with('Pizza salami', 'salami');
// => true
The check is case-sensitive. In case you need to be case-insensitive you could use strtolower()
to lowercase the entire string.
<?php // PHP 8+
$result = str_ends_with('Pizza Salami', 'salami');
// => false
$result = str_ends_with(strtolower('Pizza Salami'), 'salami');
// => true
There is one catch here, that is when checking whether your string ends with an empty string. This will always return true, since all strings end with an empty string.
PS. Besides the
str_ends_with()
function, PHP 8 also introduced a newstr_starts_with()
function.
For PHP 7
The approach for PHP 7 is somewhat more cryptic. You may use the substr_compare()
function to compare a substring against the string you wish to check from a certain offset.
<?php // PHP 7
$result = substr_compare('Pizza salami', 'salami', -strlen('salami')) === 0;
// -> true