用规则替换字符串

时间:2014-04-09 06:56:28

标签: php string replace

我的字符串包含%somestring1:somestring2%之类的字符串。我想用另一个字符串替换这些字符串,如果它的格式为%---:-----%

例如,

  $str="test content %list:UnsubscriptionLink% some other %list:subscriptionLink% test";

我想用'#'替换存在。将是

   $str="test content # some other # test";

怎么可能?

注意

我无法预测somestring1,somestring2.it是动态的。

$str="test content %list:UnsubscriptionLink% some other test";
echo preg_replace('~(%.*%)~','#',$str); //Its working

但是

$str="test content %list:UnsubscriptionLink% some other %list:UnsubscriptionLink% test";
echo preg_replace('~(%.*%)~','#',$str); //Its Not working

DEMO

2 个答案:

答案 0 :(得分:2)

使用preg_replace

执行此类操作

为您提供更新的问题

Regex Explanation

<?php
$str="test content %list:UnsubscriptionLink% some other %list:UnsubscriptionLink% test";
echo preg_replace('~(%[^%]+%)~','#',$str);

DEMO

<强>输出

test content # some other # test

答案 1 :(得分:1)

检查此 Demo Code Viper

模式Check

~%[^%]+%~

PHP

<?php   
    $str="test content %list:UnsubscriptionLink% some other %list:UnsubscriptionLink% test";
    echo preg_replace('~%[^%]+%~','#',$str);
?>

结果

test content # some other # test