Introduction

The stristr() function in PHP is used to find the first occurrence of a substring in a string case-insensitively. It returns the portion of the string starting from the first occurrence of the specified substring or false if the substring is not found. In this article, we will discuss the stristr() function in detail and how it can be used in PHP.

Understanding the stristr() function

The syntax for using the stristr() function in PHP is as follows:

stristr(string $haystack, mixed $needle, bool $before_needle = false) : string|false

Here, $haystack is the string to be searched, $needle is the substring to search for, and $before_needle is an optional parameter that specifies whether or not to return the portion of the string before the $needle.

The stristr() function returns the portion of $haystack starting from the first occurrence of $needle, case-insensitively. If $needle is not found, the function returns false.

Example Usage

Here is an example usage of the stristr() function in PHP:

<?php

$string = "The quick brown fox jumps over the lazy dog.";
$substring = "brown";

if (($result = stristr($string, $substring)) !== false) {
  echo "The substring '$substring' was found in the string '$string' and the resulting string is '$result'";
} else {
  echo "The substring '$substring' was not found in the string '$string'";
}

In the example above, we define a string $string and a substring $substring. We then use the stristr() function to search for the $substring in the $string. If the $substring is found, the function returns the portion of the $string starting from the first occurrence of the $substring and the output will be "The substring 'brown' was found in the string 'The quick brown fox jumps over the lazy dog.' and the resulting string is 'brown fox jumps over the lazy dog.'". If the $substring is not found, the function returns false and the output will be "The substring 'brown' was not found in the string 'The quick brown fox jumps over the lazy dog.'".

Conclusion

The stristr() function in PHP is a powerful tool for searching for substrings in strings case-insensitively. It is useful for many applications, such as searching for keywords in text or filtering user input. By understanding how to use the stristr() function, developers can create more efficient and effective PHP applications.

Practice Your Knowledge

What does the 'stristr' function in PHP perform?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?