Home > Backend Development > PHP Tutorial > 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?

Susan Sarandon
Release: 2024-12-27 21:47:10
Original
218 people have browsed it

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

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

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

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.

The above is the detailed content of How Can I Efficiently Check if a String Contains a Specific Word in PHP?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template