search
HomeBackend DevelopmentPHP ProblemHow to implement regular replacement in php

How to implement regular replacement in php

Dec 19, 2022 am 10:34 AM
phpregular 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])

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

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

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

这段代码可以移除在 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 
*/
?>

如果搜索到匹配项,则会返回被替换后的 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. 
*/
?>

如果 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"); 
?>

本例将输出:

$startDate = 5/27/1999

例子 4. 使用 /e 修正符

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

这将使输入字符串中的所有 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";

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

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

就是这个函数:preg_match_all

echo preg_replace("/(?:\[)(f_.[0-9]{1,3})(?:\])/i","<img  src="/static/imghwm/default1.png"  data-src="__PUBLIC__/face/f_013.png"  class="lazy"  src=&#39;__PUBLIC__/face/\${1}.png&#39; alt="How to implement regular replacement in php" >",$line[&#39;content&#39;]);

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

"How to implement regular replacement in php"  这个是我将要替换的图片地址,比如我的图片地址是这样的How to implement regular replacement in php

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

\${1} = f_013

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

<?php
$result = array();
   $n = preg_match_all("/(?:\[)(f_.[0-9]{1,3})(?:\])/i",$line[&#39;content&#39;], $result); /*返回查找到符合条件的字符串的个数*/
   if($n == 0 || $n == false)  /*如果是0或者false就说明没有表情*/
   {
    echo $line[&#39;content&#39;];
   }else
   {
     echo preg_replace("/(?:\[)(f_.[0-9]{1,3})(?:\])/i","<img  src=&#39;__PUBLIC__/face/\${1}.png&#39; alt="How to implement regular replacement in php" >",$line[&#39;content&#39;]);
   }
   ?>

推荐学习:《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
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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

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

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!