How to Check If a Word Exists in a String in PHP?

Patricia Arquette
Release: 2024-10-27 11:54:02
Original
821 people have browsed it

How to Check If a Word Exists in a String in PHP?

How to Determine the Presence of a Word in a String Using PHP

You seek a PHP function that verifies the existence of a specific word within a larger string. Consider the following pseudocode:

text = "I go to school"
word = "to"
if (word.exist(text)) {
    return true
else {
    return false
}
Copy after login

To fulfill this requirement, PHP offers several functions that cater to different scenarios.

Using strpos()

For simple instances where you only need to ascertain the word's presence, strpos() provides a straightforward approach:

<code class="php">$needle = "to";  // The word you're searching for
$haystack = "I go to school";  // The string to be searched

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

Using strstr()

If you need to perform further actions based on the result, strstr() offers more flexibility:

<code class="php">if (strstr($haystack, $needle)) {
    echo "Found!";
}</code>
Copy after login

Using preg_match()

For complex patterns involving regular expressions, preg_match() is suitable:

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

Defining a Custom Function

To package these capabilities into a custom function with default values for needle and haystack:

<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

Using str_contains() (PHP 8.0.0 and above)

PHP 8.0.0 introduced str_contains():

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

The above is the detailed content of How to Check If a Word Exists in 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