建站软件 优化软件 编程软件 网页辅助 站群程序 网站程序 图像处理 资源教程 字体下载 推荐软件


您的位置:首页 > PHP学习 > preg_replace_callback()函数的使用

preg_replace_callback()函数的使用

时间:2015-03-19 15:57:39  来源:免费模板网 作者:风雪 阅读次数 tagsphp函数

preg_replace_callback 第二个参数 为一个回调函数

例子

1
2
3
4
$string  =  'April 15, 2003' ;
$pattern  =  '/(\w+) (\d+), (\d+)/i' ;
$replacement  =  '${1}1,$3' ;
echo  preg_replace ( $pattern ,  $replacement ,  $string );

如果用preg_replace_callback 函数 改写为

1
2
3
4
5
$string  =  'April 15, 2003' ;
$pattern  =  '/(\w+) (\d+), (\d+)/i' ;
echo preg_replace_callback($pattern,  function($matches){
    return  $matches[1].','.$matches[3];
} , $string);

需求:在所有连接后面添加一个request=xxx; 这个函数比preg_replace灵活性更强,要注意它所替换的内容为整个正则表达式的内容。

$content = 'http://www.freemoban.com/aaa.php?id=111">链接2';
function add_source($matches)
{
    if(strpos($matches[1], '?'))
    {
        return 'href="'.$matches[1].'&request=xxx"';  //注意,这里和下面都加上了正则里括号外的东西:href="
    }
    else
    {
        return 'href="'.$matches[1].'?request=xxx"';
    }
}
$content = preg_replace_callback('/href=['|"](.*?)['|"]/', 'add_source', $content);


//实例二


  // 此文本是用于 2002 年的,
  // 现在想使其能用于 2003 年
  $text = "april fools day is 04/01/2002n";
  $text.= "last christmas was 12/24/2001n";

  // 回调函数
  function next_year($matches) {
    // 通常:$matches[0] 是完整的匹配项
    // $matches[1] 是第一个括号中的子模式的匹配项
    // 以此类推
    return $matches[1].($matches[2]+1);
  }

  echo preg_replace_callback(
              "|(d{2}/d{2}/)(d{4})|",
              "next_year",
              $text);

  // 结果为:
  // april fools day is 04/01/2003
  // last christmas was 12/24/2002

本文地址:https://www.freemoban.com/php/2015/0319/964.html

猜你喜欢
栏目推荐
模板推荐

Copyright:www.freemoban.com 免费模板网 All Rights Reserved 网站备案:辽ICP备19014872号-2   辽公网安备 21010602000376号  辽公网安备:42900402000182号

免责声明:本站部分资源来自互联网收集,版权归原创者所有,如果侵犯了你的权益,我们会及时删除侵权内容,联系QQ:1615187561 谢谢合作!