Home  >  Article  >  Backend Development  >  How do I check if a word exists within a string in PHP?

How do I check if a word exists within a string in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-10-29 03:01:29317browse

How do I check if a word exists within a string in PHP?

How to Check Word Existence in a String Using PHP

To determine if a particular word exists within a string in PHP, you have various options based on your specific requirements.

Simple Check:

<code class="php">$needle = "to";
$haystack = "I go to school";

if (strpos($haystack, $needle) !== false) {
    echo "Found!";
}</code>

Here, strpos() is employed to locate the position of the word within the string. If found, it returns its index, prompting the if condition to execute and print "Found!".

Case-Insensitive Check:

<code class="php">if (stripos($haystack, $needle) !== false) {
    echo "Found!";
}</code>

stripos() performs the same operation as strpos() but ignores case differences, making it case-insensitive.

Advanced Matching:

If you require more flexibility in your search, consider using regular expressions:

<code class="php">if (preg_match("/to/", $haystack)) {
    echo "Found!";
}</code>

preg_match() allows you to define complex patterns to match instead of just a single word.

Complete Function:

For a standalone function that encapsulates the word existence check:

<code class="php">function match_my_string($needle = 'to', $haystack = 'I go to school') {
    if (strpos($haystack, $needle) !== false) return true;
    else return false;
}</code>

This function takes default values for the search word and string, but you can provide custom input.

PHP 8.0.0 Improvement:

In PHP 8.0.0 and later, you can utilize the str_contains() function, which simplifies the check significantly:

<code class="php">if (str_contains($haystack, $needle)) {
    echo "Found";
}</code>

The above is the detailed content of How do I check if a word exists within a string 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