PHP strchr is an inbuilt function in PHP. It finds the first occurrence of a string in another string. Also, it returns the rest of the string after the first occurrence. In this article, we will discuss the PHP strchr Function.
Note: This function is an alias of PHP strstr Function.
Note: If you need to just check whether a string exists in another string, with faster and less memory intensive function, use PHP strpos Function.
strchr($haystack, $needle, $before_needle = false)
The PHP strchr Function expects three parameters. However, two parameters are mandatory and one is optional. The description of the parameters is as follows:
- $haystack: The first parameter to the function is the string in which you want to search in. It is a mandatory parameter.
- $needle: The second parameter to the function is also a string which you want to search. If this parameter is an integer then it will search for the character matching the ASCII value of the number.
- $before_needle: If the before_needle is set to true then the function returns the part of string before the needle. However, it is an optional parameter with the default value as false. Hence, the function returns the part of string after the first occurrence of needle.
The PHP strchr Function returns the part of the string according to before_needle parameter. However, if the search string does not exist in the original string, the function returns FALSE.
For instance, consider a basic haystack and a needle string.
<?php $haystack = 'Bringing Knowledge Together'; $needle = 'Knowledge'; //Find Knowledge in the original string $partString = strchr($haystack, $needle); echo $partString; ?>
In the above example, we search for ‘Knowledge’ in the original string. The function returns the part of the string after the first occurrence of the string.
OUTPUT: Knowledge Together
You can read more detailed examples of using this function on PHP strstr Function.
In conclusion, we discussed the PHP strchr Function. It is an alias of PHP strstr Function. Also, you can read more about it on PHP Official Documentation. Additionally, you can read about more PHP String Functions on Concatly.
Vishesh is currently working as a Senior Software Engineer at Naukri.com. He passed out of Delhi College of Engineering in 2016 and likes to play Foosball. He loves traveling and is an exercise freak. His expertise includes Java, PHP, Python, Databases, Design and Architecture.