本文实例总结了php常用正则函数。分享给大家供大家参考,具体如下:
1. mixed preg_replace(mixed pattern, mixed replacement, mixed subject, [, int limit])
函数功能:用于正则表达式的搜索和替换。
pattern:正则表达式。
replacement:替换的内容。
subject:需要匹配替换的对象。
limit:可选,指定替换的个数,如果省略 limit 或者其值为 -1,则所有的匹配项都会被替换。
补充说明
① replacement 可以包含 \\n 形式或 $n 形式的逆向引用,首选使用后者。每个此种引用将被替换为与第 n 个被捕获的括号内的子模式所匹配的文本。n 可以从 0 到 99,其中 \\0 或 $0 指的是被整个模式所匹配的文本。对左圆括号从左到右计数(从 1 开始)以取得子模式的数目。
② 对替换模式在一个逆向引用后面紧接着一个数字时(如 \\11),不能使用 \\ 符号来表示逆向引用。因为这样将会使 preg_replace() 搞不清楚是想要一个 \\1 的逆向引用后面跟着一个数字 1 还是一个 \\11 的逆向引用。解决方法是使用 \${1}1。这会形成一个隔离的 $1 逆向引用,而使另一个 1 只是单纯的文字。
③ 上述参数除 limit 外都可以是一个数组。如果 pattern 和 replacement 都是数组,将以其键名在数组中出现的顺序来进行处理,这不一定和索引的数字顺序相同。如果使用索引来标识哪个 pattern 将被哪个 replacement 来替换,应该在调用 preg_replace() 之前用 ksort() 函数对数组进行排序。
例子 1 :
<?php $str = "The quick brown fox jumped over the lazy dog."; $str = preg_replace('/\s/','-',$str); echo $str; ?>
输出结果为:
The-quick-brown-fox-jumped-over-the-lazy-dog.
例子 2 ,使用数组:
<?php $str = "The quick brown fox jumped over the lazy dog."; $patterns[0] = "/quick/"; $patterns[1] = "/brown/"; $patterns[2] = "/fox/"; $replacements[2] = "bear"; $replacements[1] = "black"; $replacements[0] = "slow"; print preg_replace($patterns, $replacements, $str); /*输出: The bear black slow jumped over the lazy dog. */ ksort($replacements); print preg_replace($patterns, $replacements, $str); /*输出: The slow black bear jumped over the lazy dog. */ ?>
例子 3 ,使用逆向引用:
<?php $str = '<a href="http://www.baidu.com/">baidu</a>其他字符<a href="http://www.sohu.com/">sohu</a>'; $pattern = "/<a\s([\s\S]*?)>([\s\S]*?)<\/a>/i"; print preg_replace($pattern, '\\2', $str); ?>
输出结果为:
baidu其他字符sohu
2. int preg_match(string $pattern, string $subject [,array &$matches [, int $flags=0 [ ,int $offset=0]]])
函数功能:搜索subject与pattern给定的正则表达式的一个匹配。
pattern:要搜索的模式,字符串类型。
subject:输入字符串。
matches:如果提供了参数matches,它将被填充为搜索结果,$matches[0]将包含完整模式匹配到文本,$matches[1]将包含第一捕获子组匹配到的文本。
flags:可以设置为PREG_OFFSET_CAPTURE,如果传递了这个标记,对于每一个出现的匹配返回时会附加字符串偏移量(相对于目标字符串的)。
注意:这会改变填充到matches数组,使其每个元素成为一个由第0个元素是匹配到的字符串,第1个元素是该匹配字符串在目标字符串subject中的偏移量。
offset:通常,搜索从目标字符串的开始,可选参数offset用于指定从目标字符串的某个未知开始搜索(单位是字节)。
3. int preg_match_all(string $pattern, string $subject [, array &$matches [, int $flags=PREG_PATTERN_ORDER [, int $offset=0]]])
函数功能:搜索subject中所有匹配pattern给定正则表达式的匹配结果并且将它们以flag指定顺序输出到matches中。
在第一个匹配找到后,子序列继续从最后一次匹配位置搜索。
pattern:要搜索的模式,字符串形式。
subject:输入字符串。
matches:多维数组,作为输出参数输出后所有匹配结果,数组排序通过flags指定。
flags:可以结合下面标记使用(注意不能同时使用PREG_PATTERN_ORDER和PREG_SET_ORDER):
PREG_PATTERN_ORDER
结果排序为$matches[0]保存完整模式的所有匹配,$matches[1] 保存第一个子组的所有匹配, 以此类推.
<?php preg_match_all("|<[^>]+>(.*)</[^>]+>|U", "<b>example: </b><div align=left>this is a test</div>", $out, PREG_PATTERN_ORDER); echo $out[0][0] . ", " . $out[0][1] . "\n"; echo $out[1][0] . ", " . $out[1][1] . "\n"; ?>
以上例程会输出:
example: ,
example: , this is a test
因此, $out[0]是包含匹配完整模式的字符串的数组,$out[1]是包含闭合标签内的字符串的数组.
PREG_SET_ORDER
结果排序为$matches[0]包含第一次匹配得到的所有匹配(包含子组),$matches[1]是包含第二次匹配到的所有匹配(包含子组)的数组, 以此类推.
<?php preg_match_all("|<[^>]+>(.*)</[^>]+>|U", "<b>example: </b><div align=\"left\">this is a test</div>", $out, PREG_SET_ORDER); echo $out[0][0] . ", " . $out[0][1] . "\n"; echo $out[1][0] . ", " . $out[1][1] . "\n"; ?>
以上例程会输出:
example: , example:
PREG_OFFSET_CAPTURE
If this flag is passed, each found match will be returned with its offset relative to the target string increased. Note that this will change the matches in Each matching result string element of , making it a 0th element is the matching result string, and the 1st element is the offset of the matching result string in the subject.
If not given Sorting flag, assuming it is set to PREG_PATTERN_ORDER.
offset: Usually, the search starts from the beginning of the target string. The optional parameter offset is used to start searching from the specified position in the target string (unit is bytes) .
I hope this article will be helpful to everyone in PHP programming.
For more articles related to summary of examples of commonly used regular functions in PHP, please pay attention to the PHP Chinese website!

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Laravel's service container and service providers are fundamental to its architecture. This article explores service containers, details service provider creation, registration, and demonstrates practical usage with examples. We'll begin with an ove

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use

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

SublimeText3 Linux new version
SublimeText3 Linux latest version