php preg_replace_callback替换多个字符串

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/daily886/article/details/86080926

<?php 
//自定义打印函数
function p($a){
    echo '<pre>';
    var_dump($a);
    echo '</pre>';
}

//需求 
//把第一个 %s 替换成 $GLOBALS['num'][0] 
//把第二个 %s 替换成 $GLOBALS['num'][1] 
//把第三个 %s 替换成 $GLOBALS['num'][2] 
//这里使用 preg_replace_callback(正则,回调函数,需要替换的字符串, 替换限制数量(-1不限制), 替换的次数)
//使用 globals全局变量
//每替换一次,删除数组里的一个值

$string = "Some numbers: one: %s; two: %s; three: %s end"; 
$GLOBALS['num'] = [1,2,3]; 
$count = 0;
$limit = -1;
$newstring = preg_replace_callback( 
    '/%s/', 
    function($match){ 
        $result = $GLOBALS['num'][0];
        unset($GLOBALS['num'][0]);
        $GLOBALS['num'] = array_values($GLOBALS['num']);
        return $result;
    }, 
    $string,
    $limit,
    $count
); 

p($newstring); 
p($count);


//需求 
//把 one two three替换成 number

$string = "Some numbers: one: 1; two: 2; three: 3 end"; 
$count = 0;
$limit = -1;
$newstring = preg_replace_callback( 
    '/one|two|three/', 
    function($match){ 
        return 'number';
    }, 
    $string,
    $limit,
    $count
); 

p($newstring); 
p($count);


//需求 
//把 one: 1, 替换成 one1: 2
//把 two: 2, 替换成 two2: 3
//把 three: 3, 替换成 three3: 4

$string = "Some numbers: one: 1; two: 2; three: 3 end"; 
$count = 0;
$limit = -1;
$newstring = preg_replace_callback( 
    '/(\w+): (\d)/', 
    function($match){ 
        return $match[1].strval($match[2]).': '.($match[2]+1);
    }, 
    $string,
    $limit,
    $count
); 

p($newstring); 
p($count);

猜你喜欢

转载自blog.csdn.net/daily886/article/details/86080926