search
HomeBackend DevelopmentPHP TutorialFunction strstr and others to find whether a string contains certain characters

  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
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.