php - preg_replace_callback替换数组问题?
阿神
阿神 2017-04-10 18:03:39
[PHP讨论组]
$tpl = preg_replace(
    ['/\s*([,;:\{\}])\s*/', '/[\t\n\r]/', '/\/\*.+?\*\//'],
    ['\\1', '', ''],   
    $tpl
);

准备使用preg_replace_callback替换掉preg_replace函数.目前只会使用preg_replace_callback替换字符串,该如何替换上述数组.

阿神
阿神

闭关修行中......

全部回复(3)
ringa_lee

数组替换preg_replace_callback没有preg_replace那么好用,但是也不是不能实现

$newText = preg_replace_callback(
    '/(.*?)(\s*([,;:\{\}])\s*)(.*?)([\t\n\r])(.*?)(\/\*.+?\*\/)(.*?)/i',
    function($match){
        $replaceArr = ['\\1', '', ''];
        return $match[1].$replaceArr[1].$match[3].$replaceArr[2].$match[5].$replaceArr[3].$match[7];
    },
    $yourText
); 
伊谢尔伦

http://php.net/manual/zh/func...

天蓬老师
$tpl = preg_replace_callback_array(
                [
                    '/\s*([,;:\{\}])\s*/' => function($matches){return $matches[1];},
                    '/[\t\n\r]/' => function($matches){return '';},
                    '/\/\*.+?\*\//' => function($matches){return '';}
                ],
                    $tpl
                )
            

后来发现使用preg_replace_callback_array来处理这中不统一的替换规则更方便.

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号