如何用两个不同的字符找到并替换字符串中的相同字符?也就是说,第一次出现一个字符,第二次出现另一个字符,一次出现整个字符串?
这就是我要做的(所以用户不需要在正文中输入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有什么东西可以一次完成这个?如何做到这一点?
$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 );