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

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

Susan Sarandon
Susan SarandonOriginal
2024-12-19 12:05:21924browse

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

How to Check if a String Contains a Specific Word

In PHP, determining whether a string contains a particular word can be achieved through various methods.

PHP 8 and str_contains

With PHP 8, the str_contains function can be used:

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

Note that str_contains returns true even if the searched substring ($needle) is empty. To prevent this, ensure that $needle is not empty before the check:

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

if ($needle !== '' && str_contains($haystack, $needle)) {
    echo 'true';
}

Pre-PHP 8 and strpos

Prior to PHP 8, the strpos function can be used:

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

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

Considerations

  • strpos returns the offset of the first occurrence of the substring, or false if not found. To check for existence, compare the result to false.
  • str_contains is case-sensitive.

The above is the detailed content of How Can I Check if a String Contains a Specific Word in PHP?. 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