"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Efficiently Check if a String Contains a Specific Word in PHP?

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

Posted on 2025-03-23
Browse:688

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

Checking String for Specific Word

The task of checking whether a string contains a particular word is a common operation in programming. Consider the following code:

$a = 'How are you?';

if ($a contains 'are')
    echo 'true';

What is the correct way to write the statement if ($a contains 'are')?

Solution: str_contains Function (PHP 8)

From PHP 8 onwards, str_contains provides a straightforward solution:

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

However, it's important to note that str_contains always returns true if the substring to search for ($needle) is empty. To avoid this, verify that $needle is non-empty before using str_contains.

Alternatives (Pre-PHP 8)

Before PHP 8, the strpos() function was used for this purpose:

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

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

In this case, strpos() returns the position of the $needle within the $haystack, or false if not found. However, using !== false is necessary since 0 is a valid position and also evaluates to falsey.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3