【问题标题】:Remove Backslash between 2 characters from string从字符串中删除 2 个字符之间的反斜杠
【发布时间】:2015-10-07 18:15:23
【问题描述】:

我只需要在 2 个字符之间替换反斜杠,引号 (") 除外

如果我有这个字符串:

When I look at you, I\understand why I live //replace
When I look at you, I "\understand why I live // No replace
When I look at you, I"\understand why I live // No replace
Sword art online\Мастера меча онлайн opening //replace Sword art online Мастера меча онлайн opening

这是一个 json 字符串,但如果我使用stripslashes,所有的反斜杠都将被删除。如果字符串没有 " 引号,我只需要删除。

非常感谢。

【问题讨论】:

  • preg_replace('~\b\\\b~', '', $str)
  • addslashes(stripslashes($string));
  • 如果你捕获所有跟在"后面的`\\`,并且匹配字符串中所有剩余的`\\`,然后替换所有捕获的`"...\\ `(比如this例子中)?

标签: php regex backslash


【解决方案1】:

你可以用这个:

$text = preg_replace('~"[^"]*"\K|\\\\~', '', $text);

或者这个:

$text = preg_replace('~"[^"]*"(*SKIP)(*F)|\\\\~', '', $text);

这两种模式使用引号之间的字符。 第一个模式使用\K 从匹配结果中删除左侧匹配的所有字符。第二个强制模式失败(使用(*F))并且不重试引号之间的字符(使用(*SKIP))。

请注意,文字反斜杠必须在模式字符串中写入\\\\。 (反斜杠为字符串转义一次,为正则表达式引擎转义一次)。

【讨论】:

    【解决方案2】:

    试试这个:

    $strings = array(
        'When I look at you, I\understand why I live',
        'When I look at you, I "\understand why I live',
        'When I look at you, I"\understand why I live',
        'Sword art online\Мастера меча онлайн opening'
    );
    
    foreach ($strings as $string) {
        $str = addslashes(stripslashes($string));
        var_dump($str);
    }
    

    【讨论】:

    • 太棒了。很高兴我能帮上忙。如果您还需要什么,请告诉我。
    猜你喜欢
    • 2015-03-28
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多