Home Backend Development PHP Problem How to perform regular expression search and replace in PHP?

How to perform regular expression search and replace in PHP?

Nov 01, 2021 pm 02:06 PM
php regular expression

在之前的文章中给大家带来了《PHP中全局正则表达式匹配及匹配数组元素(实例详解)》,其中给大家介绍了PHP中怎样通过正则表达式来进行匹配相应的元素的相关知识,本篇文章我们来看一下应该怎样执行一个正则表达式的搜索和替换。希望对大家有帮助!

"How

在之前的文章中我们了解了怎样去执行正则表达式的匹配以及怎样去检测与给定模式的数组元素,这些通过 preg_match() 函数、preg_match_all()函数和preg_grep() 函数就能够实现。但是对于字符串的操作,这些函数就有些鞭长莫及了。

字符串的替换是字符串操作中非常重要的内容之一。对于一些比较复杂的字符串替换操作,这时候我们就需要通过正则表达式的替换函数 preg_replace() 来完成正则表达式的搜索和替换工作,接下来我们就来看一下preg_replace()函数的使用吧。

<strong><span style="font-size: 20px;">preg_replace()</span></strong>函数

PHP 中的 preg_replace() 函数可以执行正则表达式的搜索和替换,是一个强大的字符串替换处理函数,可以用来处理那些比较复杂的字符串替换操作,该函数的语法格式如下:

preg_replace($pattern, $replacement, $subject [, $limit = -1 [, &$count]])
Copy after login

其中参数需要注意的是:

  • $pattern表示要搜索的模式,可以使一个字符串或字符串数组;$replacement表示用于替换的字符串或字符串数组。

  • 其中如果这个参数是一个字符串,并且 $pattern 是一个数组,那么所有的模式都使用这个字符串进行替换。如果 $pattern$replacement 都是数组,每个 $pattern 使用 $replacement 中对应的元素进行替换。如果 $replacement 中的元素比 $pattern 中的少,多出来的 $pattern 使用空字符串进行替换。

  • $subject表示要进行搜索和替换的字符串或字符串数组,如果 $subject 是一个数组,搜索和替换回在 $subject 的每一个元素上进行, 并且返回值也会是一个数组。如果 $subject 是一个数组,preg_replace() 函数会返回一个数组,其他情况下返回一个字符串。

  • $limit是个可选参数,每个模式在每个 $subject 上进行替换的最大次数。默认是 -1$count是个可选参数,如果指定,将会被填充为完成的替换次数。

如果函数 preg_replace() 搜索到匹配项,则会返回被替换后的 $subject,否则返回没有改变的 $subject。preg_replace() 函数的每个参数(除了参数 $limit)都可以是一个数组。如果参数 $pattern 和参数 $replacement 都是数组,那么该函数将以其键名在数组中出现的顺序来进行处理。如果发生错误,则返回 NULL。

接下来我们通过一个简单的示例来看一下使用 preg_replace() 函数替换字符串,示例如下:

<?php
    $string = &#39;www.php.cn&#39;;
    $pattern = &#39;/(\w+).(\w+).(\w+)/i&#39;;
    $replacement = &#39;http://$1.$2.$3/&#39;;
    echo preg_replace($pattern, $replacement, $string);
?>
Copy after login

输出结果:

"How

通过上述示例,我们需要知道的是:

参数 $replacement 中可以包含后向引用 \\n $n,语法上首选后者。每个这样的引用将被匹配到的第 n 个捕获子组捕获到的文本替换。n 可以是 0-99,\\0$0 代表完整的模式匹配文本。

捕获子组的序号计数方式为:代表捕获子组的左括号从左到右,从 1 开始数。如果要在 $replacement 中使用反斜线,必须使用 4 个"\\\\" 因为这首先是 php 的字符串,经过转义后是两个,再经过正则表达式引擎后才被认为是一个原文反斜线。

当在替换模式下工作并且后向引用后面紧跟着需要是另外一个数字,比如:在一个匹配模式后紧接着增加一个原文数字,不能使用 \\1 这样的语法来描述后向引用。

比如,\\11 将会使 preg_replace() 不能理解你希望的是一个 \\1 后向引用紧跟一个原文 1,还是一个 \\11 后向引用后面不跟任何东西。这种情况下解决方案是使用 ${1}1。这创建了一个独立的 $1 后向引用,一个独立的原文 1

当使用被弃用的 e 修饰符时,这个函数会转义一些字符即:&#39;"\NULL,然后进行后向引用替换。当这些完成后请确保后向引用解析完后没有单引号或双引号引起的语法错误,比如:&#39;strlen(\&#39;$1\&#39;)+strlen("$2")&#39;。确保符合 PHP 的字符串语法,并且符合 eval 语法。因为在完成替换后,引擎会将结果字符串作为 php 代码使用 eval 方式进行评估并将返回值作为最终参与替换的字符串。

preg_filter() 函数

上文中介绍了preg_replace() 函数,是用来执行一个正则表达式的搜索和替换的,PHP preg_filter() 函数也用于执行一个正则表达式的搜索和替换,作用与preg_replace() 函数相同,不同的是 preg_filter() 函数只返回匹配成功的结果,而 preg_replace() 返回所有结果,不管是否匹配成功。

即使如此,我们也应该了解一下preg_filter() 函数的用法,关于 preg_filter() 的工作原理和参数说明可以参考 preg_replace() 函数。

接下来我们直接通过示例来看一下preg_filter() 函数的使用,示例如下:

<?php
    echo "<pre class="brush:php;toolbar:false">";
    $arr1 = array(
        &#39;http://aaa.bbbbb.com/php/&#39;,
        &#39;http://aaa.bbbbb.com/java/&#39;,
        &#39;http://aaa.bbbbb.com/python/&#39;,
        &#39;http://www.google.com/cn/&#39;,
        &#39;http://cn.asdaf.com/&#39;,
    );
    $pattern = array(&#39;/aaa\./&#39;,&#39;/bbbbb/&#39;);
    $replacement = array(&#39;www.&#39;,&#39;baidu&#39;);
    print_r( preg_replace($pattern, $replacement, $arr1) );
    print_r( preg_filter($pattern, $replacement, $arr1) );
?>
Copy after login

输出结果:

"How

有上述示例能够看出,虽然同样是执行一个正则表达式的搜索和替换,preg_filter() 函数只返回匹配成功的结果,而 preg_replace() 返回所有结果,不管是否匹配成功。这就是preg_filter() 函数和preg_replace()函数的区别。

大家如果感兴趣的话,可以点击《PHP视频教程》、《正则表达式手册》进行更多关于PHP和正则表达式知识的学习。

The above is the detailed content of How to perform regular expression search and replace 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months 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)

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

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

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

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

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

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