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 una stringa termina con una data sottostringa
Esegue un controllo, con distinzione tra maiuscole e minuscole, per stabilire se
haystack termina con needle.
haystackLa stringa in cui effettuare la ricerca.
needle
La sottostringa da cercare in haystack.
Example #1 Uso della stringa vuota ''
<?php
if (str_ends_with('abc', '')) {
echo "Tutte le stringhe terminano con la stringa vuota";
}
?>Il precedente esempio visualizzerà:
Tutte le stringhe terminano con la stringa vuota
Example #2 Dimostrazione della distinzione tra maiuscole e minuscole
<?php
$string = 'La volpe pigra salta oltre il recinto';
if (str_ends_with($string, 'recinto')) {
echo "La stringa termina con 'recinto'\n";
}
if (str_ends_with($string, 'Recinto')) {
echo 'La stringa termina con "Recinto"';
} else {
echo '"Recinto" non è stato trovato perché le maiuscole/minuscole non corrispondono';
}
?>Il precedente esempio visualizzerà:
La stringa termina con 'recinto' "Recinto" non è stato trovato perché le maiuscole/minuscole non corrispondono
Nota:
Questa funzione è binary-safe.
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));
}
}
?>