PHP preg_filter() 函数

PHP 教程 · 2019-01-31 11:43:58

preg_filter 函数用于执行一个正则表达式搜索和替换。

语法

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

preg_filter() 等价于 preg_replace() ,但它仅仅返回与目标匹配的结果。

参数说明:

  • $pattern:要搜索的模式。可以是一个字符串或字符串数组。
  • $replacement:用于替换的字符串或字符串数组。
  • $subject:要进行搜索和替换的字符串或字符串数组。
  • $limit:可选,每个模式在每个subject上进行替换的最大次数。默认是 -1(无限)。
  • $count:可选,完成的替换次数。

实例

比较preg_filter() 和preg_replace()的示例

<?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_filter 返回值:\n"; print_r(preg_filter($pattern, $replace, $subject)); echo "preg_replace 返回值:\n"; print_r(preg_replace($pattern, $replace, $subject)); ?>

执行结果如下所示:

preg_filter 返回值:
Array
(
    [0] => A:C:1
    [1] => B:C:a
    [2] => A:2
    [3] => B:b
    [4] => A:3
    [7] => A:4
)
preg_replace 返回值:
Array
(
    [0] => A:C:1
    [1] => B:C:a
    [2] => A:2
    [3] => B:b
    [4] => A:3
    [5] => A
    [6] => B
    [7] => A:4
)

可以看出 preg_filter 只返回匹配结果,不匹配的直接忽略,而 preg_replace 将不匹配的结果 'A' 'B' 元素也一起返回。

点击查看所有 PHP 教程 文章: https://codercto.com/courses/l/5.html

查看所有标签

Writing Apache Modules with Perl and C

Writing Apache Modules with Perl and C

Lincoln Stein、Doug MacEachern / O'Reilly Media, Inc. / 1999-03 / USD 39.95

Apache is the most popular Web server on the Internet because it is free, reliable, and extensible. The availability of the source code and the modular design of Apache makes it possible to extend Web......一起来看看 《Writing Apache Modules with Perl and C》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具