Home Backend Development PHP Tutorial Summary of examples of commonly used regular functions in PHP

Summary of examples of commonly used regular functions in PHP

Jan 09, 2017 am 10:21 AM

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

   

以上例程会输出:

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 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles