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:
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 ''
|
1 2 3 4 5 |
<?php if (str_contains('abc', '')) { echo "To Checking the existence of the empty string will always return the true"; } ?> |
Case 2: Showing case-sensitivity
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $string = 'Crazy Fredrick bought many very exquisite opal jewels.'; if (str_contains($string, 'Crazy')) { echo "The string 'Crazy' was found in the string\n"; } if (str_contains($string, 'Crazy')) { echo 'The string "Crazy" was found in the string'; } else { echo '"Crazy" was not found because the case does not match'; } ?> |
The string ‘Crazy’ was found in the string
"Crazy" was not found because the case does not matchConclusion
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.