【发布时间】:2014-08-18 06:06:33
【问题描述】:
如何查找字符串中的相同字符并将其替换为两个不同的字符? IE。第一次出现一个字符,第二次出现另一个字符,一次性完成整个字符串?
这就是我想要做的(因此用户无需在正文中键入 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 有什么东西可以一口气完成吗?如何做到这一点?
【问题讨论】:
-
为什么不使用
>>代替[code]和<<作为[/code]?第三个shell怎么换>>? -
@Justinas 方便新手用户发帖。
标签: php regex preg-replace str-replace