Home php教程 php手册 preg_replace()参数均为数组多次替换的实例理解

preg_replace()参数均为数组多次替换的实例理解

Jun 13, 2016 am 11:19 AM
replace introduce about parameter classmate Example array article replace understand of

本文章给各位同学介绍关于preg_replace()参数均为数组多次替换的一些自我理解与替换次数的解决办法,有需要了解的同不可参考。  

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

pattern
要搜索的模式. 可以使一个字符串或字符串数组.

可以使用一些PCRE修饰符, 包括'e'(PREG_REPLACE_EVAL), 可以为这个函数指定.

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

replacement中可以包含后向引用n 或(php 4.0.4以上可用)$n, 语法上首选后者. 每个 这样的引用将被匹配到的第n个捕获子组捕获到的文本替换. n 可以是0-99, �和$0代表完整的模式匹配文本. 捕获子组的序号计数方式为: 代表捕获子组的左括号从左到右, 从1开始数. 如果要在replacement 中使用反斜线, 必须使用4个("", 译注: 因为这首先是php的字符串, 经过转义后, 是两个, 再经过 正则表达式引擎后才被认为是一个原文反斜线).

当在替换模式下工作并且后向引用后面紧跟着需要是另外一个数字(比如: 在一个匹配模式后紧接着增加一个原文数字), 不能使用1这样的语法来描述后向引用. 比如, 11将会使preg_replace() 不能理解你希望的是一个1后向引用紧跟一个原文1, 还是 一个11后向引用后面不跟任何东西. 这种情况下解决方案是使用${1}1. 这创建了一个独立的$1后向引用, 一个独立的原文1.

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

subject
要进行搜索和替换的字符串或字符串数组.

如果subject是一个数组, 搜索和替换回在subject 的每一个元素上进行, 并且返回值也会是一个数组.

limit
每个模式在每个subject上进行替换的最大次数. 默认是 -1(无限).

count
如果指定, 将会被填充为完成的替换次数.


是— 执行一个正则表达式的搜索和替换的用函数,平时我们用它时多是一次替换结束,今天又看php手册发现了一个较为难理解(自认为)的例子分享给大家。


    

 代码如下 复制代码

 $subject = array('1', 'a', '2', 'b', '3', 'A', 'B', '4');
 $pattern = array('/d/', '/[a-z]/', '/[1a]/');
 $replace = array('A:$0', 'B:$0', 'C:$0');
 
 echo "preg_replace returnsn

	";
 print_r(preg_replace($pattern, $replace, $subject)); 
 ?>
Copy after login

 

结果如下:

咋一看,我就看晕了

一般 若匹配模式和替换内容这两项都是数组的话它们应该相对应,如果replacement中的元素比pattern中的少, 多出来的pattern使用空字符串进行替换.

$pattern就像个扫描器,扫到匹配的就用于之对应的$replace替换

对于上例替换过程如下

 /d/扫描$subject里的1,匹配了,匹配内容为$0(也就是1)就把1替换为A:1

然后用/[a-z]/扫描A:1不匹配,就不替换,继续用[1a]扫描A:1,匹配内容为1(也就是$0),就把A:1中1换为C:1

第一项最终被替换为A:C:1

简化过程

1->A:1->A:C:1

a->B:a->B:C:a

2->A:2

b->B:b

A(没有符合匹配的就不替换了)

B(同上)

4->A:4

拿$pattern里的每一个模式依次去匹配$subject里的每一个元素,匹配到了就用与$pattern对应的那个$replace对换,如上例,可能不止一次替换

控制preg_replace替换次数

 代码如下 复制代码

$v = array('vv','bb'); $str = "vv,cc,abcde,www.bkjia.com,vv"; $str=preg_replace("/$v[0]/","".$v[0]."",$str,1); echo $str; //bb,cc,abcde,www.bkjia.com,vv

$str=preg_replace("/$v[0]/","".$v[0]."",$str,2); //bb,cc,abcde,www.bkjia.com,bb


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

How to remove duplicate elements from PHP array using foreach loop? How to remove duplicate elements from PHP array using foreach loop? Apr 27, 2024 am 11:33 AM

The method of using a foreach loop to remove duplicate elements from a PHP array is as follows: traverse the array, and if the element already exists and the current position is not the first occurrence, delete it. For example, if there are duplicate records in the database query results, you can use this method to remove them and obtain results without duplicate records.

The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy May 01, 2024 pm 12:30 PM

Methods for deep copying arrays in PHP include: JSON encoding and decoding using json_decode and json_encode. Use array_map and clone to make deep copies of keys and values. Use serialize and unserialize for serialization and deserialization.

PHP array key value flipping: Comparative performance analysis of different methods PHP array key value flipping: Comparative performance analysis of different methods May 03, 2024 pm 09:03 PM

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values ​​takes a relatively long time.

Detailed introduction of Samsung S24ai functions Detailed introduction of Samsung S24ai functions Jun 24, 2024 am 11:18 AM

2024 is the first year of AI mobile phones. More and more mobile phones integrate multiple AI functions. Empowered by AI smart technology, our mobile phones can be used more efficiently and conveniently. Recently, the Galaxy S24 series released at the beginning of the year has once again improved its generative AI experience. Let’s take a look at the detailed function introduction below. 1. Generative AI deeply empowers Samsung Galaxy S24 series, which is empowered by Galaxy AI and brings many intelligent applications. These functions are deeply integrated with Samsung One UI6.1, allowing users to have a convenient intelligent experience at any time, significantly improving the performance of mobile phones. Efficiency and convenience of use. The instant search function pioneered by the Galaxy S24 series is one of the highlights. Users only need to press and hold

Application of PHP array grouping function in data sorting Application of PHP array grouping function in data sorting May 04, 2024 pm 01:03 PM

PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group.

Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Apr 30, 2024 pm 03:42 PM

The best practice for performing an array deep copy in PHP is to use json_decode(json_encode($arr)) to convert the array to a JSON string and then convert it back to an array. Use unserialize(serialize($arr)) to serialize the array to a string and then deserialize it to a new array. Use the RecursiveIteratorIterator to recursively traverse multidimensional arrays.

PHP array multi-dimensional sorting practice: from simple to complex scenarios PHP array multi-dimensional sorting practice: from simple to complex scenarios Apr 29, 2024 pm 09:12 PM

Multidimensional array sorting can be divided into single column sorting and nested sorting. Single column sorting can use the array_multisort() function to sort by columns; nested sorting requires a recursive function to traverse the array and sort it. Practical cases include sorting by product name and compound sorting by sales volume and price.

Introduction to the online score checking platform (convenient and fast score query tool) Introduction to the online score checking platform (convenient and fast score query tool) Apr 30, 2024 pm 08:19 PM

A fast score query tool provides students and parents with more convenience. With the development of the Internet, more and more educational institutions and schools have begun to provide online score check services. To allow you to easily keep track of your child's academic progress, this article will introduce several commonly used online score checking platforms. 1. Convenience - Parents can check their children's test scores anytime and anywhere through the online score checking platform. Parents can conveniently check their children's test scores at any time by logging in to the corresponding online score checking platform on a computer or mobile phone. As long as there is an Internet connection, whether at work or when going out, parents can keep abreast of their children's learning status and provide targeted guidance and help to their children. 2. Multiple functions - in addition to score query, it also provides information such as course schedules and exam arrangements. Many online searches are available.

See all articles