PHP 正则表达式之正则处理函数小结(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这两个匹配成功的子模式。
常用的正则表达式处理函数我们就介绍完了,本节的例子可能会难一些,但希望大家还是认真的试验并体会一下,后面的正则表达式应用部分,我们会经常使用正则表达式处理函数。

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.
