Home > Backend Development > PHP Tutorial > php preg_replace替换实例讲解_PHP

php preg_replace替换实例讲解_PHP

WBOY
Release: 2016-06-01 11:58:32
Original
841 people have browsed it

复制代码 代码如下:
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$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 returns\n

Copy after login
";
 print_r(preg_replace($pattern, $replace, $subject));
 ?>
 
结果如下:

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

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template