Modified version of the original posted function. Use this one:
<?php
if (!function_exists('substr_compare')) {
function substr_compare($main_str, $str, $offset, $length = NULL, $case_insensitivity = false) {
$offset = (int) $offset;
// Throw a warning because the offset is invalid
if ($offset >= strlen($main_str)) {
trigger_error('The start position cannot exceed initial string length.', E_USER_WARNING);
return false;
}
// We are comparing the first n-characters of each string, so let's use the PHP function to do it
if ($offset == 0 && is_int($length) && $case_insensitivity === true) {
return strncasecmp($main_str, $str, $length);
}
// Get the substring that we are comparing
if (is_int($length)) {
$main_substr = substr($main_str, $offset, $length);
$str_substr = substr($str, 0, $length);
} else {
$main_substr = substr($main_str, $offset);
$str_substr = $str;
}
// Return a case-insensitive comparison of the two strings
if ($case_insensitivity === true) {
return strcasecmp($main_substr, $str_substr);
}
// Return a case-sensitive comparison of the two strings
return strcmp($main_substr, $str_substr);
}
}
?>
substr_compare
(PHP 5)
substr_compare — Comparación de 2 cadenas, segura con material binario, opcionalmente insensible a mayúsculas y minúsculas, a partir de un desplazamiento, y hasta un número límite de caracteres
Descripción
substr_compare() compara cadena_principal desde la posición desplazamiento con cadena hasta tantos caracteres como el valor de longitud .
Lista de parámetros
- cadena_principal
-
- cadena
-
- desplazamiento
-
La posición de inicio para la comparación. Si es un valor negativo, comienza contando desde el final de la cadena.
- longitud
-
La longitud de la comparación.
- insensibilidad_mayusculas
-
Si insensibilidad_mayusculas es TRUE, la comparación es insensible a mayúsculas y minúsculas.
Valores retornados
Devuelve < 0 si cadena_principal desde la posición desplazamiento es menor que cadena , > 0 si es mayor que cadena , y 0 si son iguales. Si longitud es igual o mayor que la longitud de cadena_principal y longitud se define, substr_compare() imprime una advertencia y devuelve FALSE.
Registro de cambios
| Versión | Descripción |
|---|---|
| 5.1.0 | Se agregó la posibilidad de usar un desplazamiento negativo. |
Ejemplos
Example #1 Un ejemplo de substr_compare()
<?php
echo substr_compare("abcde", "bc", 1, 2); // 0
echo substr_compare("abcde", "de", -2, 2); // 0
echo substr_compare("abcde", "bcg", 1, 2); // 0
echo substr_compare("abcde", "BC", 1, 2, true); // 0
echo substr_compare("abcde", "bc", 1, 3); // 1
echo substr_compare("abcde", "cd", 1, 2); // -1
echo substr_compare("abcde", "abc", 5, 1); // advertencia
?>
substr_compare
23-May-2005 02:07
