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
Release: 2025-01-02 16:36:39
Original
482 people have browsed it

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';
}
Copy after login

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';
}
Copy after login

Using strstr

Another option is to use strstr:

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

Using Regular Expressions

Regular expressions can also be used:

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

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template