Home >Backend Development >PHP Tutorial >How do you determine if a string contains a specific word in PHP?

How do you determine if a string contains a specific word in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-29 08:40:301068browse

How do you determine if a string contains a specific word in PHP?

Determining String Inclusion with PHP

You seek a PHP function that evaluates if a given word exists within a provided string. Let's delve into the options available:

  1. strpos() and stripos() Method: This method operates by searching for the needle (the word to be found) within the haystack (the larger string). stripos() performs a case-insensitive search.
$haystack = "I go to school";
$needle = "to";

if (strpos($haystack, $needle) !== false) {
    echo "Found!"
}
  1. strstr() and stristr(): This method also searches for the needle within the haystack, but it returns the remaining string as well.
if (strstr($haystack, $needle)) {
    echo "Found!"
}
  1. preg_match(): This regular expression approach provides more flexibility but is less performant.
if (preg_match("/{$needle}/", $haystack)) {
    echo "Found!"
}
  1. match_my_string Function: This function encapsulates the strpos() method:
function match_my_string($needle = 'to', $haystack = 'I go to school') {
    if (strpos($haystack, $needle) !== false) return true;
    else return false;
}

match_my_string($needle, $haystack);
  1. str_contains (PHP 8.0.0 ): This function offers a concise way to perform the same task:
$haystack = "I go to school";
$needle = "to";

if (str_contains($haystack, $needle)) {
    echo "Found!"
}

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