search
HomeBackend DevelopmentPHP TutorialSummary of examples of commonly used regular functions in PHP

本文实例总结了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(&#39;/\s/&#39;,&#39;-&#39;,$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 = &#39;<a href="http://www.baidu.com/">baidu</a>其他字符<a href="http://www.sohu.com/">sohu</a>&#39;;
$pattern = "/<a\s([\s\S]*?)>([\s\S]*?)<\/a>/i";
print preg_replace($pattern, &#39;\\2&#39;, $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: ,

this is a test

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:

this is a test
, this is a test

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!


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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

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 Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools