str_contains

(PHP 8)

str_containsОпределяет, содержит ли строка заданную подстроку

Описание

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

Выполняет проверку с учётом регистра, указывающую, содержится ли needle в haystack.

Список параметров

haystack

Строка для поиска.

needle

Подстрока для поиска в haystack.

Возвращаемые значения

Возвращает true, если needle содержится в haystack, false в противном случае.

Примеры

Пример #1 Пример использования пустой строки ''

<?php
if (str_contains('абв''')) {
    echo 
"Проверка существования пустой строки всегда возвращает true";
}
?>

Результат выполнения данного примера:

Проверка существования пустой строки всегда возвращает true

Пример #2 Демонстрация чувствительности к регистру

<?php
$string 
'ленивая лиса перепрыгнула через забор';

if (
str_contains($string'ленивая')) {
    echo 
"Строка 'ленивая' найдена в проверяемой строке\n";
}

if (
str_contains($string'Ленивая')) {
    echo 
'Строка "Ленивая" найдена в проверяемой строке';
} else {
    echo 
'"Ленивая" не найдена потому что регистр не совпадает';
}

?>

Результат выполнения данного примера:

Строка 'ленивая' найдена в проверяемой строке
"Ленивая" не найдена потому что регистр не совпадает

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

  • str_ends_with() - Проверяет, заканчивается ли строка заданной подстрокой
  • str_starts_with() - Проверяет, начинается ли строка с заданной подстроки
  • stripos() - Возвращает позицию первого вхождения подстроки без учёта регистра
  • strrpos() - Возвращает позицию последнего вхождения подстроки в строке
  • strripos() - Возвращает позицию последнего вхождения подстроки без учёта регистра
  • strstr() - Находит первое вхождение подстроки
  • strpbrk() - Ищет в строке любой символ из заданного набора
  • substr() - Возвращает подстроку
  • preg_match() - Выполняет проверку на соответствие регулярному выражению

add a note add a note

User Contributed Notes 4 notes

up
13
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
2
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
-7
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
-37
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