php-source-func-preg_replace_callback

概述:preg_replace_callback函数的用法

首先大概基本测试一下:

<?php
    $str = "<root><content><a href='http://www.sina.com.cn'>why not</a></content><root>";
    $regx = '/<content>(.*)<\/content>/';
    $rep_result = preg_replace_callback(
        $regx, 
        function($match){
            var_dump($match);
        },
        $str
    );
    echo $rep_result;
?>

文档介绍:自定义函数的参数是preg_match函数匹配的结果数组;函数返回值是替换之后的结果。

函数执行结果:

array(2) {
  [0] =>
  string(63) "<content><a href='http://www.sina.com.cn'>why not</a></content>"
  [1] =>
  string(44) "<a href='http://www.sina.com.cn'>why not</a>"
}
<root><root>

看到返回值结果,好难受….


<?php
    $str = "<root><content><a href='http://www.sina.com.cn'>why not</a></content><root>";
    $regx = '/<content>(.*)<\/content>/';
    $rep_result = preg_replace_callback(
        $regx, 
        function($match){
            return $match[1];
        },
        $str
    );
    echo $rep_result;
?>

回调函数返回了一个return值,用来替代查询的结果。函数执行的结果如下:

<root><a href='http://www.sina.com.cn'>why not</a><root>

函数预期还是很不错的,结合了preg_match和preg_replace两个函数的功能,到底有没有节约代码就不知道了。

测试一下替换数组的实现:

<?php
    $str = array(
        'one' => "<root><content><a href='http://www.sina.com.cn'>who am i</a></content><root>",
        'two' => "<root><content><a href='http://www.sina.com.cn'>which is</a></content><root>");
    $regx = '/<content>(.*)<\/content>/';
    $rep_result = preg_replace_callback(
        $regx, 
        function($match){
            return $match[1];
        },
        $str
    );
    var_dump($rep_result);
?>

执行结果:

array(2) {
  'one' =>
  string(57) "<root><a href='http://www.sina.com.cn'>who am i</a><root>"
  'two' =>
  string(57) "<root><a href='http://www.sina.com.cn'>which is</a><root>"
}

下次就可以使用这个函数了.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值