Home Backend Development PHP Tutorial Function strstr and others to find whether a string contains certain characters

Function strstr and others to find whether a string contains certain characters

Jul 25, 2016 am 09:05 AM

  1. /**
  2. * The following functions can be used to determine whether a string contains another string.
  3. * It is a very common operation in PHP to determine whether a string contains other characters.
  4. * If these functions happen to help you, I will be very happy.
  5. */
  6. /**
  7. * Use the strpos() function
  8. * @param unknown_type $haystack
  9. * @param unknown_type $needle
  10. * @link jbxue.com
  11. */
  12. function isInString1($haystack, $needle) {
  13. //Prevent $needle from being at the beginning
  14. $ haystack = '-_-!' . $haystack;
  15. return (bool)strpos($haystack, $needle);
  16. }
  17. /**
  18. * Use string splitting
  19. * @param unknown_type $haystack
  20. * @param unknown_type $needle
  21. */
  22. function isInString2($haystack, $needle) {
  23. $ array = explode($needle, $haystack);
  24. return count($array) > 1;
  25. }
  26. /**
  27. * I used regular expressions, but this method is not recommended, especially if $needle contains
  28. * special characters, such as ^, $,/, etc.
  29. * @param unknown_type $haystack
  30. * @param unknown_type $needle
  31. */
  32. function isInString3($haystack, $needle) {
  33. $pattern = '/ ' . $needle . '/';
  34. return (bool)preg_match($pattern, $haystack);
  35. }
  36. /**
  37. * Use the strpos() function
  38. * @param unknown_type $haystack
  39. * @param unknown_type $needle
  40. */
  41. function isInString4($haystack, $needle) {
  42. return false != = strpos($haystack, $needle);
  43. }
  44. //Test
  45. $haystack = 'I am ITBDW';
  46. $needle = 'IT';
  47. var_dump(isInString1($haystack, $needle));
Copy the code

I think the simplest one is this strpos($a, $b) !== false If $b exists in $a, it is true, otherwise it is false. The reason for using !== false (or === false) is that if $b is exactly at the beginning of $a, then the function will return int(0), then 0 is false, but $b is indeed located in $a, So use !== to determine the type, and make sure it is strictly false. I went to Zhongguancun Book Building last night and saw a book that used strpos === true to judge. This is extremely incorrect. . . The book with the error is page 107 of "PHP Job Search Guide" (updated on 2012-02-26) There are other functions natively supported by PHP, such as strstr(), stristr(), etc., which can be judged directly.

Definition and usage The strstr() function searches for the first occurrence of one string within another string.

This function returns the rest of the string (from the matching point). Returns false if the searched string is not found.

Grammar strstr(string,search)

Parameter Description string required. Specifies the string to be searched for. search required. Specifies the string to be searched for. If the argument is a number, searches for characters matching the numeric ASCII value.

Tips and Notes Note: This function is binary safe.

Note: This function is case sensitive. For case-insensitive searches, use stristr().

Example 1:

  1. echo strstr("Hello world!","world");
  2. ?>
Copy code

//Output: world!

Example 2, in this example, we will search for the character represented by the ASCII value of "o":

  1. echo strstr("Hello world!",111);
  2. ?>
Copy code

//Output: o world!

Example 3:

  1. $email = 'admin@jbxue.com';

  2. $domain = strstr($email, '@');
  3. echo $domain; // prints @ jbxue.com

  4. $user = strstr($email, '@', true); // As of PHP 5.3.0

  5. echo $user; // prints admin
  6. ?>
  7. < ;/p>
Copy code

  1. $city_str=fopen(cgi_path."/data/weather/city.dat","r");

  2. $city_ch=fread($city_str,filesize (cgi_path."/data/weather/city.dat"));
  3. $city_ch_arr=explode("|",$city_ch);
  4. //If it can match the city
  5. if(strstr($area_ga,"city" )) {
  6. Foreach ($ City_ch_arr as $ City_CH_ARR_ITEM) {
  7. IF (@Strstr ($ Area_ga, $ City_CH_ARR_ITEM)) {
  8. echo $ Area_ga. '& LT; BR & GT;' Cecho $ City_ch_arr_ITEM;
  9. $ s_city = $ City_ch_arr_item ;
  10. }
  11. }
  12. }
  13. //If you can’t find the city, see if you can find the province. Sometimes there will be a situation like this: Guangdong Province Great Wall Broadband will all belong to the provincial capital
  14. elseif(strstr($area_ga ,"Hebei")!==false){
  15. $s_city="Shijiazhuang";
  16. }elseif(strstr($area_ga,"Fujian")!==false){
  17. $s_city="Fuzhou";
  18. }elseif( strstr($area_ga,"Taiwan")!==false){
  19. $s_city="Taipei";
  20. }elseif(strstr($area_ga,"Hong Kong")!==false){
  21. $s_city="Hong Kong";
  22. }elseif(strstr($area_ga,"Guangxi")!==false){
  23. $s_city="Nanning";
  24. }elseif(strstr($area_ga,"Zhejiang")!==false){
  25. $s_city= "Hangzhou";
  26. }elseif(strstr($area_ga,"Jiangsu")!==false){
  27. $s_city="Nanjing";
  28. }elseif(strstr($area_ga,"Shandong")!==false){
  29. $s_city="Jinan";
  30. }elseif(strstr($area_ga,"Anhui")!==false){
  31. $s_city="Hefei";
  32. }elseif(strstr($area_ga,"Hunan")!= =false){
  33. $s_city="Changsha";
  34. }elseif(strstr($area_ga,"Sichuan")!==false){
  35. $s_city="Chengdu";
  36. }elseif(strstr($area_ga,"Yunnan" ")!==false){
  37. $s_city="Kunming";
  38. }elseif(strstr($area_ga,"Guangdong")!==false){
  39. $s_city="Guangzhou";
  40. }elseif(strstr($ area_ga,"Guizhou")!==false){
  41. $s_city="Guiyang";
  42. }elseif(strstr($area_ga,"Tibet")!==false){
  43. $s_city="Lhasa";
  44. }elseif (strstr($area_ga,"Xinjiang")!==false){
  45. $s_city="Urumqi";
  46. }elseif(strstr($area_ga,"Mongolia")!==false){
  47. $s_city="Hohhot" ;
  48. }elseif(strstr($area_ga,"Heilongjiang")!==false){
  49. $s_city="Harbin";
  50. }elseif(strstr($area_ga,"Liaoning")!==false){
  51. $s_city ="Shenyang";
  52. }elseif(strstr($area_ga,"Jilin")!==false){
  53. $s_city="Changchun";
  54. }elseif(strstr($area_ga,"Henan")!==false) {
  55. $s_city="Zhengzhou";
  56. }elseif(strstr($area_ga,"Hubei")!==false){
  57. $s_city="Wuhan";
  58. }elseif(strstr($area_ga,"Shanxi")! ==false){
  59. $s_city="Taiyuan";
  60. }elseif(strstr($area_ga,"Shaanxi")!==false){
  61. $s_city="Xi'an";
  62. }elseif(strstr($area_ga," Gansu")!==false){
  63. $s_city="Lanzhou";
  64. }elseif(strstr($area_ga,"Ningxia")!==false){
  65. $s_city="Yinchuan";
  66. }elseif(strstr( $area_ga,"Hainan")!==false){
  67. $s_city="Haikou";
  68. }elseif(strstr($area_ga,"Jiangxi")!==false){
  69. $s_city="Nanchang";
  70. } elseif(strstr($area_ga,"Macau")!==false){
  71. $s_city="Macau";
  72. }
  73. //If it does not exist, Guangzhou will be displayed by default, such as the local machine
  74. else{
  75. $s_city="Guangzhou ";
  76. }

Copy code

The code above: Among them, city.dat contains some cities, with a format similar to this: Guangzhou | Shenzhen | Shantou | Huizhou | Zhuhai | Jieyang | Foshan | Heyuan | Yangjiang | Maoming | Zhanjiang | Meizhou | Zhaoqing | Shaoguan | Chaozhou | Dongguan | Zhongshan | Qingyuan | Jiangmen | Shanwei | Yunfu | Zengcheng | Conghua | Lechang | Nan Xiong|Taishan|Kaiping|Heshan|Enping|Lianjiang|Leizhou|Wuchuan|Gaozhou|Huazhou|Gaoyao|Sihui|Xingning|Lufeng|Yangchun|Yingde|Lianzhou|Puning|Luoding|Beijing|Tianjin | Shanghai | Chongqing | Urumqi | Karamay | Shihezi | Alar | Tumushuk | Wujiaqu | Hami | Turpan | Aksu | Kashgar | Hotan | Yining | Tacheng | Altay | Kuitun | Bole | Changji | Fukang | Korla | Artush | Wusu | Lhasa | Shigatse | Yinchuan | Shizuishan | Wuzhong | Guyuan | Zhongwei | Hohhot | Baotou | Wuhai | Chifeng | Tongliao | Ordos | Hulunbuir | Bayannur | Ulanqab | Holin Gol|Manzhouli|Yakeshi|Zhalantun|Genhe|Ergun|Fengzhen|Xilinhot|Erenhot|Ulanhot|

Reference

  1. echo strstr('aaaaaaaaaaaboaaaaaaaaaaaboxccccccccccbcccccccccccccc','box')."
    n";
  2. //Output boxcccccccccbcccccccccccccc
  3. //Completely match the box in the middle without changing the b And stop
  4. echo strstr('aaaaaaAbaaa aaaa aaaaaaaaaaboxccccccccccccboxcccccccccc','box')."
    n";
  5. //Output boxccccccccccccboxcccccccccccc
  6. //When there are two keywords, the first stop is encountered.
  7. echo strstr ('Subscrtibe our to free newsletter about New Freew to','to')."
    n";
  8. //Output to free newsletter about New Freew to
  9. ?>
Copy code


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles