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

WBOY
Libérer: 2016-07-14 10:09:16
original
971 Les gens l'ont consulté

用正则匹配字符,如果是全部替换很简单,使用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);  
 
 
 
扩展思考,我想减低第一个结果被替换的概念怎么办呢? 有些情况,第一个被替换不是很好,只需要少量的结果是第一个被替换。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/477700.htmlTechArticle用正则匹配字符,如果是全部替换很简单,使用preg_replace就可以了。但是我现在要对得到的多个匹配成功的结果,随机替换其中的一个,这...
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!