duandong1869 2016-12-16 17:08
浏览 33
已采纳

如果没有后跟n,如何替换所有出现的\?

Seems to be relatively simple task that gets me stuck in one PHP application. I have a string which has a bunch of in it. Those are fine and need to stay there. However, there are also single occurrences of the character \ and those I need to replace or remove, let's just say with empty character without removing the ones that are followed by n.

The best I came up with was to first replace all with something else, some weird character, then replace the remaining \ with empty space and then convert back the weird character to . However, that seems to be a waste of time and resources, besides, nothing guarantees me that I'll find weird enough character that will never be encountered in the rest of the string...

Any tips?

  • 写回答

2条回答 默认 最新

  • douye8500 2016-12-16 17:17
    关注

    You need

    $s = preg_replace('~\\\\(?!n)~', '', $s);
    

    See the PHP demo:

    $s = '\
     \\t \\';
    $s = preg_replace('~\\\\(?!n)~', '', $s);
    echo $s; // => 
     t 
    

    We need 4 backslashes to pass 2 literal backslashes to the regex engine to match 1 literal backslash in the input string. The (?!n) is a negative lookahead that fails all matches of a backslash that is immediately followed with n.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟