Home Backend Development PHP Problem How to implement regular replacement in php

How to implement regular replacement in php

Dec 19, 2022 am 10:34 AM
php regular expression

php正则替换的实现方法:1、创建一个php示例文件;2、使用“preg_replace('[(/*)+.+(*/)]', '', $val);”方式执行正则表达式的搜索和替换即可。

How to implement regular replacement in php

本教程操作环境:windows10系统、PHP8.1版、DELL G3电脑

php正则替换怎么实现?

PHP正则表达式替换实现是如何的呢?首先向你介绍下PHP preg_replace,PHP preg_replace的使用是我们实现的方法,那么对于PHP正则表达式替换实现过程我们从实例入手。

PHP正则表达式替换的相关概念:

preg_replace:执行正则表达式的搜索和替换

mixed preg_replace (  
mixed pattern,  
mixed replacement,  
mixed subject [, int limit])
Copy after login

preg_replace:允许你替换字符串中匹配到你定义的正则表达式。

一个简单的注释移除功能:

preg_replace('[(/*)+.+(*/)]', '', $val);
Copy after login

这段代码可以移除在 PHP 和 CSS 中使用 /* 注释 */ 格式的多多行注释。其中的三个参数分别为正则表达式,要替换成的字符串和要替换的目标字符串(这里要做移除功能,所以是个空白字符串 -> '')。如果你想匹配次级规则,可以使用 $0 代表全部匹配,$1、$2 等,以此类推代表分别的次级规则。

在 subject 中搜索 pattern 模式的匹配项并替换为 replacement。如果指定了 limit,则仅替换 limit 个匹配,如果省略 limit 或者其值为 -1,则所有的匹配项都会被替换。

replacement 可以包含 //n 形式或(自 PHP 4.0.4 起)$n 形式的逆向引用,首选使用后者。每个此种引用将被替换为与第 n 个被捕获的括号内的子模式所匹配的文本。n 可以从 0 到 99,其中 //0 或 $0 指的是被整个模式所匹配的文本。对左圆括号从左到右计数(从 1 开始)以取得子模式的数目。

对替换模式在一个逆向引用后面紧接着一个数字时(即:紧接在一个匹配的模式后面的数字),不能使用熟悉的 //1 符号来表示逆向引用。举例说 //11,将会使 preg_replace() 搞不清楚是想要一个 //1 的逆向引用后面跟着一个数字 1 还是一个 //11 的逆向引用。本例中的解决方法是使用 /${1}1。这会形成一个隔离的 $1 逆向引用,而使另一个 1 只是单纯的文字。

PHP正则表达式替换的相关实例:

例子 1. 逆向引用后面紧接着数字的用法

<?php 
$string = "April 15, 2003"; 
$pattern = "/(/w+) (/d+), (/d+)/i"; 
$replacement = "/${1}1,/$3"; 
print preg_replace($pattern, $replacement, $string); 
/* Output 
  ====== 
April1,2003 
*/
?>
Copy after login

如果搜索到匹配项,则会返回被替换后的 subject,否则返回原来不变的 subject。

preg_replace() 的每个参数(除了 limit)都可以是一个数组。如果 pattern 和 replacement 都是数组,将以其键名在数组中出现的顺序来进行处理。这不一定和索引的数字顺序相同。如果使用索引来标识哪个 pattern 将被哪个 replacement 来替换,应该在调用 preg_replace() 之前用 ksort() 对数组进行排序。

例子 2. 在 preg_replace() 中使用索引数组

<?php 
$string =  
"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, $string); 
/* Output 
  ====== 
The bear black slow jumped over the lazy dog. 
*/
/* By ksorting patterns and replacements, 
  we should get what we wanted. */
ksort($patterns); 
ksort($replacements); 
print preg_replace($patterns, $replacements, $string); 
/* Output 
  ====== 
The slow black bear jumped over the lazy dog. 
*/
?>
Copy after login

如果 subject 是个数组,则会对 subject 中的每个项目执行搜索和替换,并返回一个数组。

如果 pattern 和 replacement 都是数组,则 preg_replace() 会依次从中分别取出值来对 subject 进行搜索和替换。如果 replacement 中的值比 pattern 中的少,则用空字符串作为余下的替换值。如果 pattern 是数组而 replacement 是字符串,则对 pattern 中的每个值都用此字符串作为替换值。反过来则没有意义了。

/e 修正符使 preg_replace() 将 replacement 参数当作 PHP 代码(在适当的逆向引用替换完之后)。提示:要确保 replacement 构成一个合法的 PHP 代码字符串,否则 PHP 会在报告在包含 preg_replace() 的行中出现语法解析错误。

例子 3. 替换数个值

<?php 
$patterns = array 
("/(19|20)(/d{2})-(/d{1,2})-(/d{1,2})/", 
          "/^/s*{(/w+)}/s*=/"); 
$replace = array 
("//3///4///1//2", "$//1 ="); 
print preg_replace  
($patterns, $replace, "{startDate} = 1999-5-27"); 
?>
Copy after login

本例将输出:

$startDate = 5/27/1999
Copy after login

例子 4. 使用 /e 修正符

<?php 
preg_replace  
("/(<//?)(/w+)([^>]*>)/e", 
"&#39;//1&#39;.strtoupper(&#39;//2&#39;).&#39;//3&#39;", 
$html_body); 
?>
Copy after login

这将使输入字符串中的所有 HTML 标记变成大写,以上的实例运行支持版本为PHP 3>= 3.0.9, PHP 4。

以前做一个项目,就是有一个问答的页面,比如说在回答或者提问的内容中插入表情。写到内容里的是表情图片的名字(而且是不带后缀的,比如:f_002.png)表情包放在项目里,我需要在取除内容的时候将里面的表情名字替换成图片。

存到数据库中的内容是这样的: 不知道[f_013] (最后面的这个[f_013]就是表情图在数据库中存放的形式)

我需要做的就是从数据库中取出内容,并且把内容中的像这样的字符 [f_013] 处理成图片地址,很显然这里需要用到正则表达式。

1.首先我得先找到这个字符串

$rule = "/(?:\[)(f_.[0-9]{1,3})(?:\])/i";
Copy after login

这个正则匹配可以帮我找到表情的字符串

2.找到后就是把这个字符串换成表情图片存放的地址,这里用到了一个函数就是正则表达式的替换。

就是这个函数:preg_match_all

echo preg_replace("/(?:\[)(f_.[0-9]{1,3})(?:\])/i","<img src=&#39;__PUBLIC__/face/\${1}.png&#39;>",$line[&#39;content&#39;]);
Copy after login

$line['content'] 这个是我从数据库中取出的内容,

"" 这个是我将要替换的图片地址,比如我的图片地址是这样的

这里面有一个非常重要的知识点: "\${1}" 它就是那个存放在数据库里面表情的字符串。

\${1} = f_013
Copy after login

我这里有我替换的一个完整代码:

Copy after login

推荐学习:《PHP视频教程

The above is the detailed content of How to implement regular replacement 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 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 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
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.

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

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

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. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

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