Statement on glibc/iconv Vulnerability

str_ends_with

(PHP 8)

str_ends_withChecks if a string ends with a given substring

Descripción

str_ends_with(string $haystack, string $needle): bool

Performs a case-sensitive check indicating if haystack ends with needle.

Parámetros

haystack

The string to search in.

needle

The substring to search for in the haystack.

Valores devueltos

Returns true if haystack ends with needle, false otherwise.

Ejemplos

Ejemplo #1 Using the empty string ''

<?php
if (str_ends_with('abc', '')) {
echo
"All strings end with the empty string";
}
?>

El resultado del ejemplo sería:

All strings end with the empty string

Ejemplo #2 Showing case-sensitivity

<?php
$string
= 'The lazy fox jumped over the fence';

if (
str_ends_with($string, 'fence')) {
echo
"The string ends with 'fence'\n";
}

if (
str_ends_with($string, 'Fence')) {
echo
'The string ends with "Fence"';
} else {
echo
'"Fence" was not found because the case does not match';
}

?>

El resultado del ejemplo sería:

The string ends with 'fence'
"Fence" was not found because the case does not match

Notas

Nota: Esta función es segura binariamente.

Ver también

  • str_contains() - Determine if a string contains a given substring
  • str_starts_with() - Checks if a string starts with a given substring
  • stripos() - Encuentra la posición de la primera aparición de un substring en un string sin considerar mayúsculas ni minúsculas
  • strrpos() - Encuentra la posición de la última aparición de un substring en un string
  • strripos() - Encuentra la posición de la última aparición de un substring insensible a mayúsculas y minúsculas en un string
  • strstr() - Encuentra la primera aparición de un string
  • strpbrk() - Buscar una cadena por cualquiera de los elementos de un conjunto de caracteres
  • substr() - Devuelve parte de una cadena
  • preg_match() - Realiza una comparación con una expresión regular

add a note

User Contributed Notes 3 notes

up
6
Reinder
10 months ago
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.
up
6
javalc6 at gmail dot com
10 months ago
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;
}
up
6
divinity76 at gmail dot com
2 years ago
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));
}
}
?>
To Top