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

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

DDD
DDDOriginal
2024-12-31 09:54:10385browse

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

How to Determine if a String Contains a Particular Word

In programming, it is often necessary to check whether a string contains a specific word or substring. One common way to do this is using the if statement, as demonstrated in your code excerpt:

$a = 'How are you?';

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

However, the code above won't work because there is no built-in "contains" method for strings in PHP. To correctly write this statement, we can use alternative methods.

PHP 8 and Later

PHP 8 introduces the str_contains function, which simplifies checking for substring existence:

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

Before PHP 8

Prior to PHP 8, you can use the strpos() function to find the occurrence of a substring:

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

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

Here, strpos() searches for the position of the substring, and a non-false result indicates its presence.

Additional Notes

  • The str_contains function is case-sensitive. To perform a case-insensitive search, you can first convert both strings to the same case.
  • The strpos() function returns 0 if the substring appears at the beginning of the string.
  • You can use the empty($needle) check to avoid empty substring matches.

The above is the detailed content of How Do 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