str_contains

(PHP 8)

str_containsDetermina se uma string contém uma substring fornecida

Descrição

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

Realiza uma busca case-sensitive indicando se needle existe em haystack.

Parâmetros

haystack

A string onde será feita a busca.

needle

A substring para ser buscada em haystack.

Valor Retornado

Retorna true se needle está em haystack, false caso contrário.

Exemplos

Exemplo #1 Usando a string vazia ''

<?php
if (str_contains('abc', '')) {
echo
"Verificando a existência de uma string vazia sempre retornará true";
}
?>

O exemplo acima produzirá:

Verificando a existência de uma string vazia sempre retornará true

Exemplo #2 Mostrando o case-sensitivity

<?php
$string
= 'A raposa preguiçosa pulou a cerca';

if (
str_contains($string, 'raposa')) {
echo
"A string 'raposa' foi encontrada na string\n";
}

if (
str_contains($string, 'Raposa')) {
echo
'A string "Raposa" foi encontrada na string';
} else {
echo
'"Raposa" não foi encontrada porque o case não corresponde';
}

?>

O exemplo acima produzirá:

A string 'raposa' foi encontrada na string
"Raposa" não foi encontrada porque o case não corresponde

Notas

Nota: Esta função é compatível com dados binários.

Veja Também

  • str_ends_with() - Verifica se uma string termina com uma substring fornecida
  • str_starts_with() - Verifica se uma string começa com uma substring fornecida
  • stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
  • strrpos() - Find the position of the last occurrence of a substring in a string
  • strripos() - Find the position of the last occurrence of a case-insensitive substring in a string
  • strstr() - Find the first occurrence of a string
  • strpbrk() - Procura na string por um dos caracteres de um conjunto
  • substr() - Retorna parte de uma string
  • preg_match() - Perform a regular expression match

add a note add a note

User Contributed Notes 5 notes

up
20
scm6079
3 years ago
For earlier versions of PHP, you can polyfill the str_contains function using the following snippet:

<?php
// based on original work from the PHP Laravel framework
if (!function_exists('str_contains')) {
    function
str_contains($haystack, $needle) {
        return
$needle !== '' && mb_strpos($haystack, $needle) !== false;
    }
}
?>
up
3
olivertasche+nospam at gmail dot com
3 years ago
The code from "me at daz dot co dot uk" will not work if the word is
- at the start of the string
- at the end of the string
- at the end of a sentence (like "the ox." or "is that an ox?")
- in quotes
- and so on.

You should explode the string by whitespace, punctations, ... and check if the resulting array contains your word OR try to test with a RegEx like this:
(^|[\s\W])+word($|[\s\W])+

Disclaimer: The RegEx may need some tweaks
up
1
juliyvchirkov at gmail dot com
2 years ago
<?php

// Polyfill for PHP 4 - PHP 7, safe to utilize with PHP 8

if (!function_exists('str_contains')) {
    function
str_contains (string $haystack, string $needle)
    {
        return empty(
$needle) || strpos($haystack, $needle) !== false;
    }
}
up
-11
kadenskinner at gmail dot com
3 years ago
<?php

$needle
= '@';
$haystack = 'user@example.com';

if (!
str_contains($haystack, $needle)){
echo
'There is not an @ in haystack';
}else{
echo
'There is an @ in haystack';
}
up
-39
me at daz dot co dot uk
3 years ago
# Watch out for aberrant partial matches

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

if (str_contains($string, 'ox')) {
    echo 'The string "ox" was found in the string because it was a partial match';
} else {
    echo '"ox" was not found';
}
//output: The string "ox" was found in the string because it was a partial match

# use spaces for full word matching

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

if (str_contains($string, ' ox ')) {
    echo 'The string " ox " was found in the string because it was a partial match';
} else {
    echo '" ox " was not found';
}
//output:  " ox " was not found
To Top