Home  >  Article  >  php教程  >  php中用正则匹配多个结果,随机替换其中一个结果

php中用正则匹配多个结果,随机替换其中一个结果

WBOY
WBOYOriginal
2016-06-13 10:55:15944browse

用正则匹配字符,如果是全部替换很简单,使用preg_replace就可以了。但是我现在要对得到的多个匹配成功的结果,随机替换其中的一个,这个就有点麻烦了。自己写了个函数解决,不知道有没有其它更好的方法。例子 “I have a dream. I have a dream. I have a dream. I have a dream.”  匹配式 '/i/'。 上面的字符串中有4个匹配结果,我只要随机替换其中的一个。i替换成hell.

我的代码如下:

 

[php]  

//正则处理函数  

function rand_replace_callback($matches) {  

    global $g_rand_replace_num, $g_rand_replace_index, $g_rand_replace_str;  

    $g_rand_replace_index++;  

    if($g_rand_replace_num==$g_rand_replace_index){  

        return $g_rand_replace_str;  

    }else {  

        return $matches[0];  

      }          

}  

  

//随机正则替换函数  如果有多个匹配的单元,随机替换其中的一个。   

//注意global $g_rand_replace_num, $g_rand_replace_index, $g_rand_replace_str;这三个全局变量,不要与其它的冲突  

//依赖一个正则处理函数 记录匹配单元总数,取一个总数范围内的随机值,在正则处理函数中判断相等则处理。  

function rand_preg_replace($pattern, $t_g_rand_replace_str, $string)  

{  

    global $g_rand_replace_num, $g_rand_replace_index, $g_rand_replace_str;  

    preg_match_all($pattern, $string, $out);$find_count = count($out[0]);  //匹配的单元总数  

    $g_rand_replace_num = mt_rand(1, $find_count);  //符合正则搜索条件的集合  

    $g_rand_replace_index = 0;  //实际替换过程中的index  

    $g_rand_replace_str = $t_g_rand_replace_str;  

    echo "现在找到符合的有{$find_count}个
";  

    $ss=preg_replace_callback($pattern,"rand_replace_callback",$string);  

    return $ss;  www.2cto.com

}  

  

$string = "I have a dream. I have a dream. I have a dream. I have a dream.";  

echo rand_preg_replace('/I/', "hell", $string);  

 

 

 

扩展思考,我想减低第一个结果被替换的概念怎么办呢? 有些情况,第一个被替换不是很好,只需要少量的结果是第一个被替换。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn