There are three functions in php that can be used to retrieve strings, namely the strstr function, strpos function, and preg_match function. In this article, we will introduce the methods of retrieving strings using these three functions.
#1. strstr function
The strstr function searches for the string to be searched from the target string; the strstr function is only used for Check whether the string exists; the strstr function is used as follows.
strstr(目标字符串,要搜索的字符串)
For example, if you execute strstr("abcdefg", "cde"), it will search for cde from abcdefg. If the corresponding string exists by searching, return the "target string", otherwise return false.
If you want to search without case sensitivity, you can use the "stristr function" to do this.
2. strpos function
The strpos function is a function that first searches for the position of the string that needs to be retrieved in the target string. Since the position of the string can be grasped in more detail than the strstr function, it is used to split the string in that part.
The usage of strpos function is as follows.
strpos(目标字符串,要搜索的字符串的位置)
For example, if you run strpos("asbabdabcasf", "abc"), the number 6 will be returned. This points to one of the abc strings. If not, false is the return value.
Note that because positions start at 0, when searching for strpos("asbabdabcasf", "asb"), the value 0 will be returned.
3. preg_match function
The preg_match function searches the regular expression pattern string from the target string.
This function can be used when you want to find a more complex string pattern than the strstr function. Use the preg_match function as follows.
返回值= preg_match(/正则表达式模式/,目标字符串)
Returns 1 if there is a string matching the regular expression pattern in the target string, otherwise the return value is 0.
Finally let’s look at a specific example
The code is as follows
<?php $a = "asfasbcasdfnaosdfaabc"; $b = "abc"; if( strstr($a, $b) ){ echo "$a中包含字符串“abc”。\n"; }else{ echo "$a中不包含字符串“abc”。\n"; } ?>
The above is the detailed content of How to search for specific characters in a string using php. For more information, please follow other related articles on the PHP Chinese website!