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

Barbara Streisand
Release: 2024-10-29 03:01:29
Original
315 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!