(PHP 4, PHP 5, PHP 7, PHP 8)
strstr — Encuentra la primera ocurrencia en un string
Devuelve una subcadena de haystack,
desde la primera ocurrencia de needle (incluida)
hasta el final del string.
Nota:
strstr() es sensible a mayúsculas y minúsculas. Para una funcionalidad idéntica, pero insensible a mayúsculas y minúsculas, consulte stristr() .
Nota:
Si el objetivo es únicamente determinar si un cierto valor de
needlese encuentra enhaystack, la función str_contains() que es más rápida y menos exigente en memoria debería ser utilizada en su lugar.
haystackEl string de entrada.
needleEl string a buscar.
Anterior a PHP 8.0.0, sineedle no es una cadena de caracteres, se
convierte en un entero y se aplica como valor ordinal de un
carácter. Este comportamiento está obsoleto a partir de PHP 7.3.0, y confiar en él
está fuertemente desaconsejado. Dependiendo del comportamiento esperado,
needle debe ser explícitamente convertido a una cadena de caracteres,
o debe realizarse una llamada explícita a chr() .
before_needle
Si es true , strstr() devuelve
la parte de haystack antes de la primera ocurrencia de
needle (needle excluido).
Devuelve la porción del string, o false si needle
no es encontrado.
| Versión | Descripción |
|---|---|
| 8.0.0 |
needle acepta ahora una cadena vacía.
|
| 8.0.0 |
Pasar un int como needle ya no es soportado.
|
| 7.3.0 |
Pasar un int como before_needle ha sido
declarado obsoleto.
|
Ejemplo #1 Ejemplo con strstr()
<?php
$email = 'name@example.com';
$domain = strstr($email, '@');
echo $domain, PHP_EOL; // Muestra: @example.com
$user = strstr($email, '@', true);
echo $user, PHP_EOL; // Muestra: name
?>
strstr() is not a way to avoid type-checking with strpos().
If $needle is the last character in $haystack, and testing $needle as a boolean by itself would evaluate to false, then testing strstr() as a boolean will evaluate to false (because, if successful, strstr() returns the first occurrence of $needle along with the rest of $haystack).
<?php
findZero('01234'); // found a zero
findZero('43210'); // did not find a zero
findZero('0'); // did not find a zero
findZero('00'); // found a zero
findZero('000'); // found a zero
findZero('10'); // did not find a zero
findZero('100'); // found a zero
function findZero($numberString) {
if (strstr($numberString, '0')) {
echo 'found a zero';
} else {
echo 'did not find a zero';
}
}
?>
Also, strstr() is far more memory-intensive than strpos(), especially with longer strings as your $haystack, so if you are not interested in the substring that strstr() returns, you shouldn't be using it anyway.
There is no PHP function just to check only _if_ $needle occurs in $haystack; strpos() tells you if it _doesn't_ by returning false, but, if it does occur, it tells you _where_ it occurs as an integer, which is 0 (zero) if $needle is the first part of $haystack, which is why testing if (strpos($needle, $haystack)===false) is the only way to know for sure if $needle is not part of $haystack.
My advice is to start loving type checking immediately, and to familiarize yourself with the return value of the functions you are using.
Cheers.Lookout for logic inversion in old code!
In PHP 8, if the needle is an empty string, this function will return 0 (not false), implying the first character of the string matches the needle. Before PHP 8, it would return false when the needle is an empty string.
There other string functions that are affected by similar issues in PHP 8: strpos(), strrpos(), stripos(), strripos(), strchr(), strrchr(), stristr(), and this function, strstr()
If you are checking if the return value === false then you will be misled by this new behaviour. You also need to check if the needle was an empty string. Basically, something like this:
<?php
$result = $needle ? strstr($haystack, $needle) : false;
?>For those in need of the last occurrence of a string:
<?php
function strrstr($h, $n, $before = false) {
$rpos = strrpos($h, $n);
if($rpos === false) return false;
if($before == false) return substr($h, $rpos);
else return substr($h, 0, $rpos);
}
?>Been using this for years:
<?php
/**
*
* @author : Dennis T Kaplan
*
* @version : 1.0
* Date : June 17, 2007
* Function : reverse strstr()
* Purpose : Returns part of haystack string from start to the first occurrence of needle
* $haystack = 'this/that/whatever';
* $result = rstrstr($haystack, '/')
* $result == this
*
* @access public
* @param string $haystack, string $needle
* @return string
**/
function rstrstr($haystack,$needle)
{
return substr($haystack, 0,strpos($haystack, $needle));
}
?>
You could change it to:
rstrstr ( string $haystack , mixed $needle [, int $start] )
<?php
function rstrstr($haystack,$needle, $start=0)
{
return substr($haystack, $start,strpos($haystack, $needle));
}
?>For the needle_before (first occurance) parameter when using PHP 5.x or less, try:
<?php
$haystack = 'php-homepage-20071125.png';
$needle = '-';
$result = substr($haystack, 0, strpos($haystack, $needle)); // $result = php
?>