In PHP, string is one of the common data types, and we often need to operate and find strings. Among them, finding a string is one of the most basic functions. Among PHP's string functions, the strchr() function is a very practical function that is used to find the position of a certain character in a string and return a substring composed of the character and all subsequent characters.
The basic syntax of the strchr() function:
strchr(string,char,mode)
Among them, string represents the string to be searched, char represents the character to be searched, and mode represents the search mode, which is an optional parameter. Among them, the optional values of mode are as follows:
If the search is successful, a substring consisting of the matching character and all the characters following it is returned; if not found, FALSE is returned.
Here are some examples of using the strchr() function to find a string:
$str = "hello world"; $substr = strchr($str, 'l'); echo $substr; // 输出:lo world
In the above example , $str represents the string to be searched, and 'l' represents the character to be searched. Since the mode parameter is not specified, it defaults to 0, which means finding the first matching character 'l'. After the search is successful, the substring 'lo world' consisting of the matching character 'l' and all characters following it is returned.
$str = "hello world"; $substr = strchr($str, 'l', 1); echo $substr; // 输出:ld
In the above example, $str represents the string to be searched, 'l' represents the character to be searched, 1 Indicates finding the last matching character. Since the mode parameter is passed in, the last matching character 'l' is found. After the search is successful, the substring 'ld' consisting of the matching character 'l' and all characters following it is returned.
It should be noted that if you want to find the null character (''), you need to use double quotes, as shown below:
$str = "hello world!"; $substr = strchr($str, ""); echo $substr; // 输出:hello world!
The above is about using the strchr() function in PHP Some basic introduction and examples of finding strings. The main advantage of the strchr() function is that it is simple and easy to use, and it is very convenient to find strings or characters. During the development process, we can use this function flexibly according to actual needs to quickly and accurately find the target string or character position.
The above is the detailed content of Find string using strchr() function in PHP. For more information, please follow other related articles on the PHP Chinese website!