dongli2000
2016-04-18 13:12
浏览 72
已采纳

正则表达式用于转义尚未转义的单引号

I want to replace ' with \' but not \' since they are already escaped.

图片转代码服务由CSDN问答提供 功能建议

我想用 \'替换'但不是 \',因为它们已经被转义。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dpub33855 2016-04-18 13:20
    已采纳

    Pretty simple with lookarounds:

    (?<!\\)'
    

    See a demo on regex101.com.
    You'll need to escape the backslashes as well for PHP:

    <?php
    $string = "I want to replace ' with \' but not \' since they are already escaped";
    $regex = "~(?<!\\\)'~";
    
    echo preg_replace($regex, "\\'", $string);
    # Output: I want to replace \' with \' but not \' since they are already escaped
    
    ?>
    

    See a demo on ideone.com.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题