PHP string contains | PHP str_contains Function with Example

Summary: In this tutorial, we learn how to checks if a string is contained in another string. To check php string contains used PHP str_contains function.

Overview PHP string contains

  • str_contains is used to determine if a string contains a given substring.
  • str_contains checks if a string is contained in another string and it returns a boolean value such as true and false value, whether or not the string was found.

The typical path to check if a string is contained in another is generally done by using the PHP functions strpos or strstr. as a result of this feature is such a common use-case in almost every project, furthermore, it should deserve its own dedicated function: str_contains.

Repurposing strpos and strstr for this use-case have some downsides. Either, they are:

  • not very intuitive for a reader
  • easy to get wrong (especially with the !== comparison) or hard to remember for new PHP developers.

Because of that, several PHP frameworks provide a helper function for this behavior, because it is so ubiquitous. furthermore, this indicates the significance & the necessity pretty well.

Syntax:

str_contains ( string $haystack , string $needle ) : bool
.
Note: str_contains takes a $haystack and a $needle as arguments, checks if $needle is found in $haystack, and returns a boolean value such as true/false whether or not the $needle was found.
This function is binary-safe.
Return Values

Returns true if needle is in haystack, false otherwise.

Example of PHP String Contains

Case 1: using the empty string ''
Output: to Checking the existence of the empty string will always return the true
Case 2: Showing case-sensitivity

Output:
The string ‘Crazy’ was found in the string
"Crazy" was not found because the case does not match

Conclusion

In this tutorial, you have learned how to checks if a string is contained in another string. To check php string contains used PHP str_contains function.