Home Backend Development PHP Tutorial Example analysis of commonly used regular functions in PHP

Example analysis of commonly used regular functions in PHP

May 29, 2018 am 09:38 AM
php function Case Analysis

这篇文章主要介绍了php常用正则函数,结合实例形式总结分析了php正则表达式常用函数,包括preg_replace、preg_match及preg_match_all函数的功能、使用方法与相关注意事项,需要的朋友可以参考下

本文实例总结了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;
?>
Copy after login

输出结果为:

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.
*/
?>
Copy after login

例子 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);
?>
Copy after login

输出结果为:

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><p align=left>this is a test</p>",
  $out, PREG_PATTERN_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";
echo $out[1][0] . ", " . $out[1][1] . "\n";
?>
Copy after login

以上例程会输出:

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><p align=\"left\">this is a test</p>",
  $out, PREG_SET_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";
echo $out[1][0] . ", " . $out[1][1] . "\n";
?>
Copy after login

以上例程会输出:

example: , example:

this is a test

, this is a test

PREG_OFFSET_CAPTURE

如果这个标记被传递, 每个发现的匹配返回时会增加它相对目标字符串的偏移量. 注意这会改变matches中的每一个匹配结果字符串元素, 使其 成为一个第0个元素为匹配结果字符串, 第1个元素为 匹配结果字符串在subject中的偏移量.

如果没有给定排序标记, 假定设置为PREG_PATTERN_ORDER.

offset:通常,查找时从目标字符串的开始位置开始,可选参数offset用于从目标字符串中指定位置开始搜索(单位是字节)。

以上就是本文的全部内容,希望对大家的学习有所帮助。


相关推荐:

常用的PHP函数整理

PHP函数重载分析及实例

php函数的引用与返回

The above is the detailed content of Example analysis of commonly used regular functions in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles