search
HomeBackend DevelopmentPHP TutorialPHP 正则表达式之正则处理函数小结(preg_match,preg_match_all,p_PHP

正则表达式

前面我们已经学习了正则表达式的基础语法,包括了定界符、原子、元字符和模式修正 符。实际上正则表达式想要起作用的话,就必须借用正则表达式处理函数。本节我们就来介绍一下PHP中基于perl的正则表达式处理函数,主要包含了分割, 匹配,查找,替换等等处理操作,依旧是配合示例讲解,让我们开始吧。

和正则表达式一样,正则表达式处理函数不能够独立使用,而这必须相结合,才能够完成特定的功能。在前面我们也说过,基于perl的正则表达式要快于POXIS正则表达式处理函数,所以我们只介绍以preg开头的基于perl的正则表达式。注意:在能偶使用字符串函数处理的时候,就不要使用正则表达式来处理字符串,因为字符串处理函数更快。

下面我们来看一些常用的正则表达式处理函数。

1,preg_match()函数。

函数preg_match()执行一个正则表达式匹配,其定义如下:

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

实际上就是搜索subject中匹配pattern的部分, 以保存在数组matches中.请看示例:
复制代码 代码如下:
$pattern = '/.*?/';
$string = 'welcome to phpfunsdsadsadas';
if (preg_match($pattern, $string, $arr)) {
echo "正则表达式{$pattern}和字符串{$string}匹配成功
";
print_r($arr);
} else {
echo "正则表达式{$pattern}和字符串{$string}匹配失败";
}
?>


2,preg_match_all()函数。

函数preg_match_all()函数执行一个全局正则表达式匹配,其定义和preg_match()函数一致,只不过匹配了全部结果。请看示例:
复制代码 代码如下:
$pattern = '/.*?/';
$string = 'welcome to phpfunsdsadsadas';
if (preg_match_all($pattern, $string, $arr)) {
echo "正则表达式{$pattern}和字符串{$string}匹配成功
";
print_r($arr);
} else {
echo "正则表达式{$pattern}和字符串{$string}匹配失败";
}
?>

依旧是上面的示例(只换了正则处理函数为preg_match_all()),但是匹配的结果数组内容不一样了。

3, preg_replace()函数

函数preg_replace()执行一个正则表达式替换,其定义如下:

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

实际上就是搜索subject中匹配pattern的部分, 以replacement进行替换.其中limit指的是每个模式在每个subject上进行替换的最大次数. 默认是 -1(无限). 如果指定count,将会被填充为完成的替换次数.

注意:

A,如果subject是一个数组, preg_replace()返回一个数组, 其他情况下返回一个字符串.

B,如果匹配被查找到, 替换后的subject被返回, 其他情况下返回没有改变的subject. 如果发生错误, 返回NULL .

C,子模式可以应用到参数replacement中,使用方式为\n或者${n}。(在正则表达式的模式中我们只能使用\n的形式来获取已经匹配的子模式,切记!)

D,如果使用模式修正符e,则参数replacement中可以解析函数。(在其它的正则表达式处理函数中,模式修正符e均被忽略!)

请看下面的综合示例:
复制代码 代码如下:
$pattern = '/(php)|(mysql)/e';
$string = '这个字符串中的php和mysql被替换成大写的了!';
$result = preg_replace($pattern, 'strtoupper("${1}\2")', $string, -1, $count);
echo $result.'
';
echo $count;
?>

上例中,我们使用了模式修正符e,这样的话strtoupper()函数就可以当作字符串被解析,这就是模式修正符e的作用!而参数${1}和\2分别是子模式1和子模式2。上例的作用就是将字符串$string中匹配到的子模式php和mysql替换成大写字母!

4,preg_split()函数。

preg_split执行一个正则表达式分隔字符串。其定义如下:

array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )

实际上就是将subject按照pattern分割,返回分割后的数组。其中,limit将限制分隔得到的子串最多只有limit个, 返回的最后一个子串将包含所有剩余部分.limit值为-1, 0或null时都代表"不限制"。

我们来看一个示例:
复制代码 代码如下:
$pattern = '/

(.*?)/';
$string = '这个字符串中的

php

mysql

被分割了!';
$result = preg_split($pattern, $string, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($result);
?>

上例中,我们使用了常量PREG_SPLIT_DELIM_CAPTURE设 置返回结果中包含子模式(如果设置为PREG_SPLIT_NO_EMPTY,preg_split()将进返回分隔后的非空部分。)我们如果把上例中正 则表达式的括号去掉,则结果中不再包含php和mysql这两个匹配成功的子模式。

常用的正则表达式处理函数我们就介绍完了,本节的例子可能会难一些,但希望大家还是认真的试验并体会一下,后面的正则表达式应用部分,我们会经常使用正则表达式处理函数。
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
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development 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.

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.