search
HomeBackend DevelopmentPHP Tutorialphp中的字符串和正则表达式

一、字符串类型的特点

    1、PHP是弱类型语言,其他数据类型一般都可以直接应用于字符串函数操作。

   1: <?php 
   2: echo substr("123456",2,4);  //输出345
   3: echo substr(123456,2,4);    //输出345
   4: echo hello;                 //先查找hello常量,若没找到,将hello看做字符串使用
   5: ?>

    2、字符串可以作为“数组”,是字符的集合。

   1: <?php 
   2: $str = "www.ido321.com";
   3: echo $str[0];
   4: echo $str[1];
   5: echo $str[2];
   6: ?>

          但是字符串不是真的数组,不能使用数组的函数.如count($str)不会返回字符串长度。PHP引擎无法区分字符和数组,产生二义性。自PHP4起,已经用花括号替代方括号。

   1: <?php 
   2: //为保证向后兼容,方括号仍然可以使用
   3: $str = "www.ido321.com";
   4: echo $str{0};
   5: echo $str{1};
   6: echo $str{2};
   7: ?>

    3、双引号变量解析

          在PHP中,当用双引号或者定界符定义字符串时,其中的变量会被解析。

   1: <?php 
   2: $arr = array('name' => "dwqs",'add' => "www.ido321.com");
   3: echo "$arr[name]";  //可以解析,但是在方括号中不能使用引号
   4: //echo "$arr['name']"; 错误
   5: echo "{$arr['name']}";  //可以解析,用花括号包含元素,name不带引号也是可以的
   6:  
   7: //假设存在对象$square
   8: echo "$square->width"; //可以解析
   9: echo "$square->width00 cent"; //不可以解析,用花括号解决
  10: echo "{$square->width}width00 cent"; //可以解析
  11: ?>

 

二、字符串输出函数


三、常用的字符串格式函数


   PS:PHP的字符串处理函数大部分不对源字符串做修改,而是返回新的字符串

 

四、正则表达式

        正则表达式描述了一种字符串匹配的模式,通过这个模式在特定的函数中对字符串进行匹配、查找、替换和分隔等操作,由原子、元字符和模式修正符三部分组成的文字模式。

        在PHP中,有两套正则的处理函数库:PCRE和POSIX。前者以preg_前缀命名,与Perl兼容;后者以ereg_前缀命名。二者功能相似,但PCRE的效率略高。

        与Perl语言兼容的正则表达式处理函数:

1、语法

            1.1  定界符:在与Perl兼容的正则函数中使用模式时,必须给模式加上定界符。除了字母、数字和反斜线(\)之外的任何字符都可以作为定界符号

   1: <?php 
   2: //以下正则合法
   3: echo $m1 = '/    <pre style="代码" class="precsshei">   4: echo $m2 = '|(\d{3})-\d|Sm';
   5: echo $m3 = '!^(?i)php[34]!';
   6: echo $m4 = '{^\s+(\s+)?$}';
   7: ?>

             1.2  原子:原子包含了普通字符,如字母、数字;非打印字符,如空格、回车;特殊字符和元字符,如引号、*、+等,必须用”\”进行转义;自定义原子表,如[apj]、[a-z];通用字符类型,如\d、\D。

   1: <?php 
   2: //下面二者等价,匹配e-mail
   3: $mail1 = '/^[0-9a-zA-Z]+@[0-9a-zA-Z]+(\.[0-9a-zA-Z]+){0,3}$/';
   4: $mail2 = '/^\w+@\w+(\.\w+){0,3}$/';
   5: ?>

              1.3  元字符:用于构建正则表达式的具有特殊含义的字符。Perl可以使用各种元字符来搜索匹配,如*、+、?.常见的元字符如下

1.4  模式修正符:在正则的定界符之外使用,扩展正则在匹配、替换等方面的功能。

     2.与Perl兼容的正则表达式函数

         2.1  preg_match(string pattern,string subject[,array matches]):用于对字符串的查找和匹配。参数说明:

                pattern是正则,subject是需要处理的字符串,可选的matches用于保存于pattern的各个子模式的匹配结果,matches[0]保存了与pattern匹配的整体内容,matches[1]保存了pattern中第一个小括号中匹配的内容,以此类推。

   1: <?php 
   2: header("content-type:text/html;charset=utf8");
   3: $pattern = '/(http):\/\/(www)\.([^\.\/]+)\.(com|net|org)/i';
   4: $subject = "我的博客:http://www.ido321.com";
   5: if(preg_match($pattern, $subject,$matches)){
   6:     echo "搜索的URL是:".$matches[0]."<br>";  //数组第1个元素保存整个匹配结果
   7:     echo "URL中的协议是:".$matches[1]."<br>";//数组第2个元素保存第1个字表达式
   8:     echo "URL中的主机是:".$matches[2]."<br>";//数组第3个元素保存第2个字表达式
   9:     echo "URL中的域名是:".$matches[3]."<br>";//数组第4个元素保存第3个字表达式
  10:     echo "URL中的顶域是:".$matches[4]."<br>";//数组第5个元素保存第4个字表达式
  11: }
  12: ?>

结果

    preg_match_all()与preg_match()函数类似,不同的是前者会一直匹配到字符串末尾,后者在第一次匹配后就停止匹配。

             2.2  preg_grep(string pattern,array iput):匹配数组中的元素,返回与正则匹配的数组单元。参数说明:

                     pattern是正则,input是需要匹配的数组。

   1: <?php 
   2: $arr = array('Linux RedHat9.0','Apache2.2.9','MySQL5.0.51','PHP5.2.6','LAMP','100');
   3: $version = preg_grep('/^[a-zA-Z]+(\d|\.)+$/',$arr);
   4:  
   5: //输出:Array([1]=>Apache2.2.9 [2]=>MySQL5.0.51 [3]=>PHP5.2.6)
   6: print_r($version); 
   7: ?>

             2.3  preg_replace(mixed pattern,mixed replacement,mixed subject[,int limit]):字符串替换。说明:

                     该函数会在subject中搜索与pattern的匹配项,并用replacement替换。limit用于限制匹配的次数,即替换的次数。

   1: <?php 
   2: $pattern = '/]*?/is';
   3: $text = '这个文本有<b>粗体</b>和<u>带有下划线</u>以及<i>斜体</i>';
   4: echo preg_replace($pattern,"",$text);  //将所有HTML标记替换为空
   5: echo preg_replace($pattern,"",$text,2); //值替换前2个HTML标记
   6: ?>

              2.4  preg_split(string pattern,string subject[,int limit[,int flags]]):对字符串进行分割。说明:

                     函数返回一个数组。数组元素包含subject中与pattern匹配作为边界所分割的字符串,limit含义见2.3,flags含义请参考文档。

   1: <?php 
   2: //按任数量的空格分割字符串
   3: $kerwords = preg_split("/[\s,]+/","hypertext language,programming");
   4:  
   5: //输出:Array([0]=>hypertext [1]=>language,[2[=>programming)
   6: print_r($kerwords);
   7: ?>

来源:http://www.ido321.com/612.html

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
What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

What is the importance of setting the httponly flag for session cookies?What is the importance of setting the httponly flag for session cookies?May 03, 2025 am 12:10 AM

Setting the httponly flag is crucial for session cookies because it can effectively prevent XSS attacks and protect user session information. Specifically, 1) the httponly flag prevents JavaScript from accessing cookies, 2) the flag can be set through setcookies and make_response in PHP and Flask, 3) Although it cannot be prevented from all attacks, it should be part of the overall security policy.

What problem do PHP sessions solve in web development?What problem do PHP sessions solve in web development?May 03, 2025 am 12:02 AM

PHPsessionssolvetheproblemofmaintainingstateacrossmultipleHTTPrequestsbystoringdataontheserverandassociatingitwithauniquesessionID.1)Theystoredataserver-side,typicallyinfilesordatabases,anduseasessionIDstoredinacookietoretrievedata.2)Sessionsenhances

What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

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 Tools

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

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.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools