I found myself needing to find the first position of multiple needles in one haystack. So I wrote this little function:
<?php
function multineedle_stripos($haystack, $needles, $offset=0) {
foreach($needles as $needle) {
$found[$needle] = stripos($haystack, $needle, $offset);
}
return $found;
}
// It works as such:
$haystack = "The quick brown fox jumps over the lazy dog.";
$needle = array("fox", "dog", ".", "duck")
var_dump(multineedle_stripos($haystack, $needle));
/* Output:
array(3) {
["fox"]=>
int(16)
["dog"]=>
int(40)
["."]=>
int(43)
["duck"]=>
bool(false)
}
*/
?>
stripos
(PHP 5)
stripos — Encuentra la posición de la primera aparición de un substring insensible a mayúsculas y minúsculas en in string
Descripción
$haystack
, string $needle
[, int $offset = 0
] )
Encuentra la posición numérica de la primera aparición del
needle (aguja) en el string haystack (pajar).
A diferencia de strpos(), stripos() es insensible a mayúsculas y minúsculas.
Parámetros
-
haystack -
El string en donde buscar.
-
needle -
Nótese que
needlepuede ser un string de uno o más caracteres.Si
needleno es un string, será convertido a un integer y se aplicará como el valor ordinal de un caracter. -
offset -
Si se específica, la búsqueda iniciará en éste número de caracteres contados desde el inicio del string. A diferencia de strrpos() y strripos(), el offset no puede ser negativo.
Valores devueltos
Devuelve la posición donde la aguja existe, en relación al inicio del
string haystack (independiente del offset).
También tener en cuenta que las posiciones de inicio de los string empiezan en 0 y no 1.
Devuelve FALSE si no fue encontrada la aguja.
Esta función puede
devolver el valor booleano FALSE, pero también puede devolver un valor no booleano que se
evalúa como FALSE. Por favor lea la sección sobre Booleanos para más información. Use
el operador === para comprobar el valor devuelto por esta
función.
Ejemplos
Ejemplo #1 Ejemplos de stripos()
<?php
$findme = 'a';
$mystring1 = 'xyz';
$mystring2 = 'ABC';
$pos1 = stripos($mystring1, $findme);
$pos2 = stripos($mystring2, $findme);
// No, 'a' sin duda no está en 'xyz'
if ($pos1 === false) {
echo "The string '$findme' was not found in the string '$mystring1'";
}
// Nótese el uso de ===. Usar sólo == no funcionará como se espera
// debido a que la posición de 'a' es el 0º (primer) caracter.
if ($pos2 !== false) {
echo "We found '$findme' in '$mystring2' at position $pos2";
}
?>
Notas
Nota: Esta función es segura binariamente.
Ver también
- strpos() - Encuentra la posición de la primera ocurrencia de un substring en un string
- 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
- stristr() - strstr insensible a mayúsculas y minúsculas
- substr() - Devuelve parte de una cadena
- str_ireplace() - Versión insensible a mayúsculas y minúsculas de str_replace
this would to work with any language, i hope.
tested on czech (eastern europe) lang.
<?php
/****************************************
* SAFE HIGHLIGHT
****************************************/
/**
* function finds and encase every string in a $needleArr array with
* strings $shearLft (from the left side) and $shearRgt (guess from which
* side).
* already encased needles are IGNORED for any other step, so order
* of needles in $needleArr is pretty important.
*
* function is searching needles in case-insensitive mode,
* but case in the subject is saved.
*
* can you do it better? so, do it.
*
* @param array $needleArr array of needles
* @param string $shearLft left shear
* @param string $shearRgt right shear
* @param string $subject subject
* @param string $encoding encoding ('utf-8' is default)
*
* @author griffin
*/
function safeHighlight( $needleArr, $shearLft, $shearRgt, $subject, $encoding = 'utf-8')
{
// encoding
$e = $encoding;
// oh, no needles
if( !is_array( $needleArr))
return $subject;
// empty keys throw-off, only unique, reindex
$nA = array_values(
array_unique(
array_diff( $needleArr, array(''))
)
);
// needle count
if( !($nC = count( $nA)))
return $subject; // nothing to hl
// shear length
if( !(($rLL = mb_strlen( $rL = $shearLft, $e))
+ ($rRL = mb_strlen( $rR = $shearRgt, $e))))
return $subject; // no shears
// subject length
if( !($sL = mb_strlen( $s = $subject, $e)))
return null; // empty subject
// subject in lowercase (we need to aviod
// using mb_stripos due to PHP version)
$sW = mb_strtolower( $s, $e);
// masking ~ 0=not changed, 1=changed
$m = str_repeat( '0', $sL);
// loop for each needle
for( $n=0; $n<$nC; $n++)
{
// needle string loWercase
$nW = mb_strtolower( $nA[ $n], $e);
$o = 0; // offset
$nL = mb_strlen( $nW, $e); // needle length
// search needle
while( false !== ($p = mb_strpos( $sW, $nW, $o, $e)))
{
// oh hurrey, needle found on $p position
// is founded needle already modified? (in full-length)
for( $q=$p; $q<($p+$nL); $q++)
if( $m[ $q])
{
// ai, caramba. already modified, jump over
$o+= $nL;
// continue for while() loop - not for for() loop!
continue 2;
}
// explode subject and mask into three parts
// partA|needle|partB
$sE[0] = mb_substr( $s, 0, $p, $e);
$sE[1] = mb_substr( $s, $p, $nL, $e);
$sE[2] = mb_substr( $s, $p+$nL, $sL-$p-$nL, $e);
// mask
// partA|partB (needle not needed)
$mE[0] = mb_substr( $m, 0, $p, $e);
$mE[1] = mb_substr( $m, $p+$nL, $sL-$p-$nL, $e);
// apply shears
$sE[1] = $rL.$sE[1].$rR;
// update sunject length
$sL+= $rLL + $rRL;
// update mask
$m = $mE[0] . str_repeat( '1', $rLL + $nL + $rRL) . $mE[1];
// implode into a subject
$s = implode( $sE);
// update lowercase subject
$sW = mb_strtolower( $s, $e);
// increase offset
$o+= $rLL + $nL + $rRL;
// end of string reached
if( $o>=$sL)
break;
} // while()
} // for( $n=0; $n<$nC; $n++)
// oouu yeaaa, kick the subject out of the function
return $s;
} // function safeHighlight()
/****************************************
* END: SAFE HIGHLIGHT
****************************************/
?>
