PHP.mk документација

str_contains

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.str-contains.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.str-contains.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
str_contains

Референца за `function.str-contains.php` со подобрена типографија и навигација.

function.str-contains.php

str_contains

(PHP 8)

str_containsОдреди дали стринг содржи даден подстринг

= NULL

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

Проверува дали стринг започнува со даден подстринг needle е содржано во haystack.

Параметри

haystack

Најди ја нумеричката позиција на првото појавување на

needle

започнува со haystack.

Вратени вредности

Патеката до PHP скриптата што треба да се провери. true if needle е во haystack, false otherwise.

Примери

Подстринг за пребарување во ''

<?php
if (str_contains('abc', '')) {
echo
"Checking the existence of the empty string will always return true";
}
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

Checking the existence of the empty string will always return true

Пример #1 Користење на празен стринг

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

if (
str_contains($string, 'lazy')) {
echo
"The string 'lazy' was found in the string\n";
}

if (
str_contains($string, 'Lazy')) {
echo
'The string "Lazy" was found in the string';
} else {
echo
'"Lazy" was not found because the case does not match';
}

?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

The string 'lazy' was found in the string
"Lazy" was not found because the case does not match

Белешки

Забелешка: Пример #4 Користење на контексти на потоци

Види Исто така

  • str_ends_with() - Одреди дали низата содржи дадена подниза
  • str_starts_with() - Проверува дали низата завршува со дадена подниза
  • stripos() Пример #3 Користење на поместување
  • strrpos() - Проверува дали низата започнува со дадена подниза
  • strripos() - Најди ја позицијата на последното појавување на подниза во низа
  • strstr() - Најди ја првата појава на низа
  • strpbrk() - Пребарај низа за било кој од сет на знаци
  • substr() - Врати дел од низа
  • preg_match() - Изврши совпаѓање со регуларен израз

Белешки од корисници Управување со PDO конекции

scm6079
пред 4 години
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;
    }
}
?>
aisunny7 точка xy на gmail точка com
пред 4 години
The polyfill that based on original work from the PHP Laravel framework had a different behavior;

when the $needle is `""` or `null`:
php8's will return `true`;
but, laravel'str_contains will return `false`;

when php8.1, null is deprecated, You can use `$needle ?: ""`;
harl на gmail точка ком
пред 2 години
A couple of functions for checking if a string contains any of the strings in an array, or all of the strings in an array:

<?php
function str_contains_any(string $haystack, array $needles): bool
{
    return array_reduce($needles, fn($a, $n) => $a || str_contains($haystack, $n), false);
}

function str_contains_all(string $haystack, array $needles): bool
{
    return array_reduce($needles, fn($a, $n) => $a && str_contains($haystack, $n), true);
}
?>

str_contains_all() will return true if $needles is an empty array. If you think that's wrong, show me a string in $needles that DOESN'T appear in the $haystack, and then look up "vacuous truth".

(By swapping haystacks and needles in the body of these functions you can create versions that check if a needle appears in any/all of an array of haystacks.)
Анкјер
пред 2 години
This function doesn't always produce the expected results if you have a needle that isn't UTF-8 but are looking for it in a UTF-8 string. This won't be a concern for most people, but if you are mixing old and new data, especially if reading data from a file, it could be an issue.

Here's a "mb_*"-esque function that searches the string:

<?php
function mb_str_contains(string $haystack, string $needle, $encoding = null) {
    return $needle === '' || mb_substr_count($haystack, $needle, (empty($encoding) ? mb_internal_encoding() : $encoding)) > 0;
}
?>

I used mb_substr_count() instead of mb_strpos() because mb_strpos() will still match partial characters as it's doing a binary search.

We can compare str_contains to the above suggested function:

<?php
// Some Unicode Kanji (漢字はユニコード)
$string = hex2bin('e6bca2e5ad97e381afe383a6e3838be382b3e383bce38389');

// Some Windows-1252 characters (ãƒ)
$contains = hex2bin('e383');
// ^ file_get_contents() produces the same data when it is saved as "ANSI" in Notepad on Windows, so this is not that unrealistic. The only reason to use hex2bin here is to mix character sets without having to use multiple files.

// A character that actually exists in our string. (ー)
$contains2 = hex2bin('e383bc');

echo " = Haystack: ".var_export($string, true)."\r\n";
echo " = Needles:\r\n";
echo "   + Windows-1252 characters\r\n";
echo "     - Results:\r\n";
echo "       >    str_contains: ".var_export(str_contains($string, $contains), true)."\r\n";
echo "       > mb_str_contains: ".var_export(mb_str_contains($string, $contains), true)."\r\n";
echo "   + Valid UTF-8 character\r\n";
echo "     - Results:\r\n";
echo "       >    str_contains: ".var_export(str_contains($string, $contains2), true)."\r\n";
echo "       > mb_str_contains: ".var_export(mb_str_contains($string, $contains2), true)."\r\n";
echo "\r\n";
?>

Output:

 = Haystack: '漢字はユニコード'
 = Needles:
   + Windows-1252 characters
     - Results:
       >    str_contains: true
       > mb_str_contains: false
   + Valid UTF-8 character
     - Results:
       >    str_contains: true
       > mb_str_contains: true

It's not completely foolproof, however. For instance, ド in Windows-1252 will match ド from the above string. So it's still best to convert the encoding of the parameters to be the same first. But, if the character set isn't known/can't be detected and you have no choice but to deal with dirty data, this is probably the simplest solution.
juliyvchirkov на gmail точка com
пред 4 години
<?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;
    }
}
olivertasche+nospam на gmail точка com
пред 5 години
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
drupalista точка com точка br на gmail точка com
3 години пред
private function contains(array $needles, string $type, string $haystack = NULL, string $filename = NULL) : bool {
        if (empty($needles)) return FALSE;
        if ($filename)
            $haystack = file_get_contents($filename);

        $now_what = function(string $needle) use ($haystack, $type) : array {
            $has_needle = str_contains($haystack, $needle);
            if ($type === 'any' && $has_needle)
                return ['done' => TRUE, 'return' => TRUE];

            if ($type === 'all' && !$has_needle)
                return ['done' => TRUE, 'return' => FALSE];

            return ['done' => FALSE];
        };

        foreach ($needles as $needle) {
            $check = $now_what($needle);
            if ($check['done'])
                return $check['return'];
        }
        return TRUE;
    }

    function containsAny(array $needles, string $haystack = NULL, string $filename = NULL) : bool {
        return self::contains($needles, 'any', $haystack, $filename);
    }

    function containsAll(array $needles, string $haystack = NULL, string $filename = NULL) : bool {
        return self::contains($needles, 'all', $haystack, $filename);
    }
Навигација

Прелистувај сродни теми и функции.

На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.