Home  >  Article  >  Backend Development  >  How to Check If a Word Exists in a String in PHP?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-27 11:54:02749browse

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
}

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>

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>

Using preg_match()

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

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

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>

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>

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!

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