douzui6173 2011-07-15 02:40
浏览 93

preg_replace第一个匹配模式包括斜杠

How to remove first pattern match when string content "/"

$a = "abc/def";
$b = "abc/def/ghi/abc/def";

$result = "/ghi/abc/def"; when replace with "abc/def" only look for the fist match


I try this but is not work.
$x  = preg_replace('/'.$a.'/', '', $b, 1);
  • 写回答

1条回答 默认 最新

  • dtziv24262 2011-07-15 11:18
    关注

    You have to keep in mind that first argument of preg_replace is a RegEx pattern, so you can't pass just any string to it.

    First you need to escape all regex characters with function preg_quote

    Try:

    $a = "abc/def";
    $b = "abc/def/ghi/abc/def";
    
    $pattern = preg_quote($a, '/'); // second argument allows us to escape delimiter chars, too
    
    $x  = preg_replace("/$pattern/", '', $b, 1);
    
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料