PHP替换:用不同的文本查找和替换相同的字符

时间:2014-08-18 06:06:33

标签: php regex preg-replace str-replace

如何在包含两个不同字符的字符串中查找和替换相同的字符? I.E.第一次出现一个字符,第二次出现另一个字符,一次出现整个字符串?

这就是我尝试做的事情(因此用户无需在体内输入html):我在这里使用了preg_replace,但我还是愿意使用其他任何内容。

$str = $str = '>>Hello, this is code>> Here is some text >>This is more code>>';

$str = preg_replace('#[>>]+#','[code]',$str);

echo $str;

//output from the above
//[code]Hello, this is code[code] Here is some text [code]This is more code[code]

//expected output
//[code]Hello, this is code[/code] Here is some text [code]This is more code[/code]

但问题是,>>都被[code]取代。是否有可能以某种方式将第一个>>替换为[code],将第二个>>替换为[/code]以获得整个输出?

php是否可以一次性完成这项工作?怎么办呢?

1 个答案:

答案 0 :(得分:2)

$str = '>>Hello, this is code>> Here is some text >>This is more code>>';
echo preg_replace( "#>>([^>]+)>>#", "[code]$1[/code]", $str );

如果您输入以下内容,则上述操作将失败:

>>Here is code >to break >stuff>>

要解决此问题,请使用否定前瞻:

#>>((?!>[^>]).+?)>>#

将是你的模式。

echo preg_replace( "#>>((?!>[^>]).+?)>>#", "[code]$1[/code]", $str );
相关问题