1.preg_match()
函数原型:int preg_match (string $pattern, string $content [, array $matches])
preg_match ()函数在$content字符串中搜索与$pattern给出的正则表达式相匹配的内容。如果提供了$matches,则将匹配结果放入其 中。$matches[0]将包含与整个模式匹配的文本,$matches[1]将包含第一个捕获的与括号中的模式单元所匹配的内容,以此类推。该函数只 作一次匹配,最终返回0或1的匹配结果数。代码6.1给出preg_match()函数的一段代码示例。
代码6.1 日期时间的匹配
代码如下:
<?php //需要匹配的字符串。date函数返回当前时间 $content = "Current date and time is ".date("Y-m-d h:i a").", we are learning PHP together."; //使用通常的方法匹配时间 if (preg_match ("//d{4}-/d{2}-/d{2} /d{2}:/d{2} [ap]m/", $content, $m)) { echo "匹配的时间是:" .$m[0]. "/n"; } //由于时间的模式明显,也可以简单的匹配 if (preg_match ("/([/d-]{10}) ([/d:]{5} [ap]m)/", $content, $m)) { echo "当前日期是:" .$m[1]. "/n"; echo "当前时间是:" .$m[2]. "/n"; } ?>
这是一个简单动态文本串匹配实例。假设当前系统时间是“2006年8月17日13点25分”,将输出如下的内容。
匹配的时间是:2006-08-17 01:25 pm
当前日期是:2006-08-17
当前时间是:01:25 pm
2.ereg()和eregi()
ereg()是POSIX扩展库中正则表达式的匹配函数。eregi()是ereg()函数的忽略大小写的版 本。二者与preg_match的功能类似,但函数返回的是一个布尔值,表明匹配成功与否。需要说明的是,POSIX扩展库函数的第一个参数接受的是正则 表达式字符串,即不需要使用分界符。例如,代码6.2是一个关于文件名安全检验的方法。
代码6.2 文件名的安全检验
代码如下:
<?php $username = $_SERVER['REMOTE_USER']; $filename = $_GET['file']; //对文件名进行过滤,以保证系统安全 if (!ereg('^[^./][^/]*$', $userfile)) { die('这不是一个非法的文件名!'); } //对用户名进行过滤 if (!ereg('^[^./][^/]*$', $username)) { die('这不是一个无效的用户名'); } //通过安全过滤,拼合文件路径 $thefile = "/home/$username/$filename"; ?>
通常情况下,使用与Perl兼容的正则表达式匹配函数perg_match(),将比使用ereg()或eregi()的速度更快。如果只是查找一个字符串中是否包含某个子字符串,建议使用strstr()或strpos()函数。
正则表达式的替换
1.ereg_replace()和eregi_replace()
函数原型:string ereg_replace (string $pattern, string $replacement, string $string)
string eregi_replace (string $pattern, string $replacement, string $string)
ereg_replace()在$string中搜索模式字符串$pattern,并将所匹配结果替换 为$replacement。当$pattern中包含模式单元(或子模式)时,$replacement中形如“/1”或“$1”的位置将依次被这些子 模式所匹配的内容替换。而“/0”或“$0”是指整个的匹配字符串的内容。需要注意的是,在双引号中反斜线作为转义符使用,所以必须使用“//0”,“ //1”的形式。
eregi_replace()和ereg_replace()的功能一致,只是前者忽略大小写。代码6.6是本函数的应用实例,这段代码演示了如何对程序源代码做简单的清理工作。
代码6.6 源代码的清理
代码如下:
<?php $lines = file('source.php'); //将文件读入数组中 for($i=0; $i<count($lines); $i++) { //将行末以“//”或“#”开头的注释去掉 $lines[$i] = eregi_replace("(////|#).*$", "", $lines[$i]); //将行末的空白消除 $lines[$i] = eregi_replace("[ /n/r/t/v/f]*$", "/r/n", $lines[$i]); } //整理后输出到页面 echo htmlspecialchars(join("",$lines)); ?>
2.preg_replace()
函数原型:mixed preg_replace (mixed $pattern, mixed $replacement, mixed $subject [, int $limit])
preg_replace较ereg_replace的功能更加强大。其前三个参数均可以使用数组;第四个参数$limit可以设置替换的次数,默认为全部替换。代码6.7是一个数组替换的应用实例。
代码6.7 数组替换
代码如下:
<?php //字符串 $string = "Name: {Name}<br>/nEmail: {Email}<br>/nAddress: {Address}<br>/n"; //模式 $patterns =array( "/{Address}/", "/{Name}/", "/{Email}/" ); //替换字串 $replacements = array ( "No.5, Wilson St., New York, U.S.A", "Thomas Ching", "tom@emailaddress.com", ); //输出模式替换结果 print preg_replace($patterns, $replacements, $string); ?>
输出结果如下。
Name: Thomas Ching", Email: tom@emailaddress.com Address: No.5, Wilson St., New York, U.S.A
在preg_replace的正则表达式中可以使用模式修正符“e”。其作用是将匹配结果用作表达式,并且可以进行重新运算。例如:
代码如下:
<?php $html_body = “<HTML><Body><h1 id="TEST">TEST</h1>My Picture<Img src=”my.gif”></Body></HTML>”; //输出结果中HTML标签将全部为小写字母 echo preg_replace ( "/(<//?)(/w+)([^>]*>)/e", "'//1'.strtolower('//2').'//3'", //此处的模式变量//2将被strtolower转换为小写字符 $html_body); ?>
提示
preg_replace函数使用了Perl兼容正则表达式语法,通常是比ereg_replace更快的替代方案。如果仅对字符串做简单的替换,可以使用str_replace函数。

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor

WebStorm Mac version
Useful JavaScript development tools

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.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
