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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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)

Hot Topics

Java Tutorial
1671
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO) How do you prevent SQL Injection in PHP? (Prepared statements, PDO) Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles