Home  >  Article  >  Backend Development  >  PHP preg_replace replacement example explanation

PHP preg_replace replacement example explanation

高洛峰
高洛峰Original
2017-01-20 09:37:211063browse

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

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

<?php
 $subject = array(&#39;1&#39;, &#39;a&#39;, &#39;2&#39;, &#39;b&#39;, &#39;3&#39;, &#39;A&#39;, &#39;B&#39;, &#39;4&#39;);
 $pattern = array(&#39;/\d/&#39;, &#39;/[a-z]/&#39;, &#39;/[1a]/&#39;);
 $replace = array(&#39;A:$0&#39;, &#39;B:$0&#39;, &#39;C:$0&#39;);

 echo "preg_replace returns\n<pre/>";
 print_r(preg_replace($pattern, $replace, $subject));
 ?>

结果如下:

php preg_replace替换实例讲解

咋一看,我就看晕了
一般 若匹配模式和替换内容这两项都是数组的话它们应该相对应,如果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对换,如上例,可能不止一次替换

更多php preg_replace替换实例讲解相关文章请关注PHP中文网!

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