Three functions strstr, stristr, and strpos are provided in php for character search. The usage of these three functions is somewhat different. Next we will introduce the relevant functions.
Syntax:
String strstr (string haystack, string needle)
Returns the string starting from needle to ending in haystack.
If no value is returned, that is, no needle is found, FALSE is returned.
Note: This function is case sensitive.
Instance 1
| The Code is as follows: |
Copy code |
$ City_str = fopen (cgi_path. "/data/weather/city. dat", "r "); $ City_ch = fread ($ city_str, filesize (cgi_path. "/data/weather/city. dat ")); $ City_ch_arr = explode ("|", $ city_ch ); // If it matches the city If (strstr ($ area_ga, "city ")){ Foreach ($ city_ch_arr as $ city_ch_arr_item ){ If (@ strstr ($ area_ga, $ city_ch_arr_item )){ Echo $ area_ga. '<br> '; Echo $ city_ch_arr_item; $ S_city = $ city_ch_arr_item; } } } // If the city cannot be found, check if the province can be found. Sometimes the following situation occurs: Guangdong Great Wall broadband belongs to the Provincial Government. Elseif (strstr ($ area_ga, "Hebei ")! = False ){ $ S_city = "Shijiazhuang "; } |
In city. dat, some city formats are as follows:
Guangzhou | Shenzhen | Shantou | Huizhou
For more details, see http://www.bKjia. c0m/phper/18/8304359 e6918876b45d02c200bc8f193.htm
Stristr ()The function is used to locate the first occurrence of a string in another string.
If successful, the rest of the string is returned (from the matching point ). If this string is not found, false is returned.
| The Code is as follows: |
Copy code |
<? Php Echo stristr ("Hello world! "," WORLD "); ?> Output: World! |
Strpos Introduction
Returns a character relative to the first two, and a position relative to the first two. Because the location may be 0, it is more appropriate to use = false to determine if the search fails.
Strpos has better performance. If you only judge whether the needle is in the string haystack, strpos is better. It will occupy less memory and get faster execution speed. However, strpos does not support special characters, such as Chinese characters.
Example
| The Code is as follows: |
Copy code |
<? Php Echo strpos ("Hello world! "," Wo "); ?> Output: 6 |
Note: This function is case sensitive. Use the stripos () function to perform case-insensitive searches.
Based on the above example, we can conclude that
Strstr is case-sensitive. It is found from characters. If yes, true is returned. Otherwise, false is returned.
Stristr characters are case-insensitive. Start with the character. If yes, true is returned. Otherwise, false is returned.
Strpos is case-sensitive. After strpos is successfully searched, it returns a location. Because the location may be 0, it is more appropriate to use = false to determine if the search fails.