Home >Backend Development >PHP Tutorial >How Can I Check if a PHP String Contains a Specific Word?

How Can I Check if a PHP String Contains a Specific Word?

DDD
DDDOriginal
2025-01-02 16:36:39541browse

How Can I Check if a PHP String Contains a Specific Word?

Checking String Contains Specific Word

In PHP, verifying if a string contains a particular word can be achieved using built-in functions or string manipulation techniques.

Using str_contains (PHP 8 )

PHP 8 introduces the str_contains function for checking string containment:

if (str_contains('How are you', 'are')) {
    echo 'true';
}

Note: str_contains considers an empty needle as true, so ensure it's not empty before using it.

Using strpos

For PHP versions prior to 8, strpos can be employed:

$haystack = 'How are you?';
$needle = 'are';

if (strpos($haystack, $needle) !== false) {
    echo 'true';
}

Using strstr

Another option is to use strstr:

if (strstr('How are you?', 'are') !== false) {
    echo 'true';
}

Using Regular Expressions

Regular expressions can also be used:

if (preg_match('/are/', 'How are you?')) {
    echo 'true';
}

The above is the detailed content of How Can I Check if a PHP String Contains a Specific Word?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn