先看一个例子:
<?php$string = 'April 15, 2003';$pattern = '/(\w+) (\d+), (\d+)/i';$replacement = '${1}1,$3';echo preg_replace($pattern, $replacement, $string);?>
例子的结果是:April1,2003
函数preg_replace ( mixed pattern, mixed replacement, mixed subject [, int limit])
在 subject 中搜索 pattern 模式的匹配项并替换为 replacement。如果指定了 limit,则仅替换 limit 个匹配,如果省略 limit 或者其值为 -1,则所有的匹配项都会被替换。
replacement可以包含\\n形式或$n形式的逆向引用,n可以为0到99,\\n表示匹配pattern第n个子模式的文本,\\0表示匹配整个pattern的文本。
所谓“子模式”就是:$pattern参数中被圆括号括起来的正则表达式(pattern即为模式)。
对上面例子中的 $replacement = '${1}1,$3';
因为当在替换模式下工作并且后向引用后面紧跟着需要是另外一个数字, 不能使用\\1这样的语法来描述后向引用。\\11将会使preg_replace() 不能理解你希望的是一个\\1后向引用紧跟一个原文1,还是 一个\\11后向引用后面不跟任何东西。 这种情况下解决方案是使用\${1}1。 这创建了一个独立的$1后向引用, 一个独立的原文1。
再看一个例子:
<?php $string = "Is is the cost of of gasoline going up up"; $pattern = "/\b([a-z]+) \\1\b/i"; //这里的\\1不能使用\$1或$1 $str = preg_replace($pattern, "\\1", $string); //这里的\\1可以使用\$1或$1,引用第一个子匹配 echo $str; ?>
结果为:Is the cost of gasoline going up 去掉了重复的内容。
例中的子表达式就是圆括号内的项。\b匹配单词的开始或结束。+匹配重复一次或更多次。
该子表达式匹配的是一个或多个字母字符的单词,即由'[a-z]+'匹配的。
该正则表达式的第二部分是对前面所捕获的子匹配的引用,也就是由附加表达式所匹配的第二次出现的单词,用'\\1'来引用第一个子匹配,第一个\是转义符。
i是正则表达式中的修正符。i:忽略大小写。
扩展:一个常见的面试题
在file.txt中按行存放着这样的一些数字
0013223544456
013423545456
1372-35--45456
132245-44556
13723-584456
1392-3544-456
132-255444-56
0132-275444-56
希望对其进行处理:除去首位的0,除去字符串中包含的-符号,并且将手机号码处理成132****456格式,处理后保存在newfile.txt文件中。
我的方法是:
<?php$fp = fopen("file.txt", "r");$newf = fopen("newfile.txt", "w"); while(! feof($fp)) { $fgets = fgets($fp);$fgets = preg_replace('/^0*|\D/', '', $fgets);$pattern = "/(1\d{1,2})\d\d(\d{0,3})/";$replacement = "\$1****\$3";$fgets = preg_replace($pattern, $replacement, $fgets);$text = $fgets."\r\n";fwrite($newf, $text);} fclose($fp); fclose($newf);?>
newfile.txt中最总结果是:
132****456
134****456
137****456
132****556
137****456
139****456
132****456
132****456

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

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 originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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.