In case you are using an older version of PHP, you can define and use the following function:function endsWith($haystack, $needle) { $length = strlen($needle); return $length > 0 ? substr($haystack, -$length) === $needle : true;}
(PHP 8)
str_ends_with — Verifica se uma string termina com uma substring fornecida
Realiza uma verificação sensível a maiúsculas/minúsculas indicando se
haystack
termina com needle
.
haystack
A string onde será feita a busca.
needle
A substring para procurar em haystack
.
Exemplo #1 Usando a string vazia ''
<?php
if (str_ends_with('abc', '')) {
echo "Toda string termina com uma string vazia";
}
?>
O exemplo acima produzirá:
Toda string termina com uma string vazia
Exemplo #2 Mostrando a sensibilidade a maiúsculas/minúsculas
<?php
$string = 'A raposa preguiçosa pulou a cerca';
if (str_ends_with($string, 'cerca')) {
echo "A string termina com 'cerca'\n";
}
if (str_ends_with($string, 'Cerca')) {
echo 'A string termina com "Cerca"';
} else {
echo '"Cerca" não foi encontrada porque a letra maiúscula não corresponde';
}
?>
O exemplo acima produzirá:
A string termina com 'cerca' "Cerca" não foi encontrada porque a letra maiúscula não corresponde
Nota: Esta função é compatível com dados binários.
In case you are using an older version of PHP, you can define and use the following function:function endsWith($haystack, $needle) { $length = strlen($needle); return $length > 0 ? substr($haystack, -$length) === $needle : true;}
In PHP7 you may want to use:if (!function_exists('str_ends_with')) { function str_ends_with($str, $end) { return (@substr_compare($str, $end, -strlen($end))==0); }}AFAIK that is binary safe and doesn't need additional checks.
this is the fastest php7-implementation i can think of, it should be faster than javalc6 and Reinder's implementations, as this one doesn't create new strings (but theirs does)<?phpif (! function_exists('str_ends_with')) { function str_ends_with(string $haystack, string $needle): bool { $needle_len = strlen($needle); return ($needle_len === 0 || 0 === substr_compare($haystack, $needle, - $needle_len)); }}?>