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
Release: 2024-10-29 08:40:30
Original
1058 people have browsed it

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!"
}
Copy after login
  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!"
}
Copy after login
  1. preg_match(): This regular expression approach provides more flexibility but is less performant.
if (preg_match("/{$needle}/", $haystack)) {
    echo "Found!"
}
Copy after login
  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);
Copy after login
  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!"
}
Copy after login

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!

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