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 — Determina si una cadena termina con un substring dado
Realiza una verificación sensible a mayúsculas y minúsculas que indica si
haystack
(pajar) termina con needle
(aguja).
haystack
El string en la que se realiza la búsqueda.
needle
El substring a buscar en haystack
.
Ejemplo #1 Con un string vacío ''
<?php
if (str_ends_with('abc', '')) {
echo "Todas las cadenas terminan con la cadena vacía";
}
?>
El resultado del ejemplo sería:
Todas las cadenas terminan con la cadena vacía
Ejemplo #2 Demostración de la sensibilidad a mayúsculas y minúsculas
<?php
$string = 'The lazy fox jumped over the fence';
if (str_ends_with($string, 'fence')) {
echo "La cadena termina con 'fence'\n";
}
if (str_ends_with($string, 'Fence')) {
echo 'La cadena termina con "Fence"';
} else {
echo '"Fence" no fue encontrado porque las mayúsculas y minúsculas no coinciden';
}
?>
El resultado del ejemplo sería:
La cadena termina con 'fence' "Fence" no fue encontrado porque las mayúsculas y minúsculas no coinciden
Nota: Esta función es segura binariamente.
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)
<?php
if (! 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));
}
}
?>