【问题标题】:PHP replace : find and replace the same characters with different textPHP替换:用不同的文本查找并替换相同的字符
【发布时间】: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


【解决方案1】:
$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 );

【讨论】:

  • 你是对的。你的第二个模式处理得很好。在您发布答案后,我碰巧正在测试,但从未想过用户在>> 字符串之间输入>
  • 你能帮我做一件小事吗?我怎样才能添加一些只有在有 2 个 >> 而不是更多或更少的情况下才能替换的东西。例如:$str = '>>Hello, this is code>> Here is some text >>>This is more code>>>.'; echo preg_replace( "#>>{2}((?!>[^>]).+?)>>{2}#", "[code]$1[/code]", $str ); 仅将字符串替换为 >> 而不是 >>>。我添加了一个 {2},我认为它应该可以工作,但没有用。
猜你喜欢
  • 2019-12-27
  • 2011-03-12
  • 2011-04-28
  • 2020-08-31
  • 2022-10-13
  • 2011-07-08
  • 2013-07-10
  • 1970-01-01
  • 2022-01-08
相关资源
最近更新 更多