PHP 8.4.0 RC3 available for testing

strstr

(PHP 4, PHP 5, PHP 7, PHP 8)

strstrEncontra a primeira ocorrência de uma string

Descrição

strstr(string $haystack, string $needle, bool $before_needle = false): string|false

Retorna parte da string haystack iniciando a partir da primeira ocorrência de needle (inclusive) até o final de haystack.

Nota:

Este função é sensível a maiúsculas/minúsculas. Para pesquisas insensíveis a maiúsculas/minúsculas, use stristr().

Nota:

Se for necessário apenas determinar se um needle em particular ocorre dentro de haystack, a função mais rápida e que consome menos memória, str_contains(), deve ser usada em seu lugar.

Parâmetros

haystack

A string de entrada.

needle

A string sendo procurada.

Antes do PHP 8.0.0, se needle não for uma string, ela será convertida para um número inteiro e aplicada como o valor ordinal de um caractere. Este comportamento tornou-se defasado a partir do PHP 7.3.0 e depender dele é altamente desaconselhado. Dependendo do comportamento pretendido, o parâmetro needle deve ser explicitamente convertido em string ou uma chamada explícita para chr() deve ser realizada.

before_needle

Se for igual a true, strstr() retorna a parte de haystack antes da primeira ocorrência de needle (excluindo este último).

Valor Retornado

Retorna a parte da string ou false se needle não for encontrada.

Registro de Alterações

Versão Descrição
8.0.0 O parâmetro needle agora aceita uma string vazia.
8.0.0 Passar um int em needle não é mais suportado.
7.3.0 Passar um int em needle tornou-se defasado.

Exemplos

Exemplo #1 Exemplo de strstr()

<?php
$email
= 'nome@exemplo.com';
$domain = strstr($email, '@');
echo
$domain; // mostra @exemplo.com

$user = strstr($email, '@', true);
echo
$user; // mostra nome
?>

Veja Também

  • stristr() - strstr insensível a maiúsculas/minúsculas
  • strrchr() - Encontra a última ocorrência de um caractere em uma string
  • strpos() - Encontra a posição da primeira ocorrência de uma substring em uma string
  • strpbrk() - Procura na string por um dos caracteres de um conjunto
  • preg_match() - Realiza uma correspondência com expressão regular

adicione uma nota

Notas Enviadas por Usuários (em inglês) 8 notes

up
45
laszlo dot heredy at gmail dot com
10 years ago
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.
up
11
Gevorg Melkumyan
3 years ago
Don't confuse this function with strtr ) I lost like 1 hour on that
up
2
Julian Egelstaff
1 year ago
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;
?>
up
13
xslidian at lidian dot info
11 years ago
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);
}
?>
up
17
gruessle at gmail dot com
13 years ago
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));
}

?>
up
9
w3b_monk3y at yahoo dot com
15 years ago
If you want to emulate strstr's new before_needle parameter pre 5.3 strtok is faster than using strpos to find the needle and cutting with substr. The amount of difference varies with string size but strtok is always faster.
up
9
brett dot jr dot alton at gmail dot com
16 years ago
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
?>
up
-3
trent dot renshaw at objectst dot com dot au
9 years ago
> root at mantoru dot de

PHP makes this easy for you. When working with domain portion of email addresses, simply pass the return of strstr() to substr() and start at 1:

substr(strstr($haystack, '@'), 1);
To Top