dsk95913 2012-03-05 17:22
浏览 22
已采纳

尽管preg_quote,工作正则表达式模式在PHP中不起作用

The pattern below seems to work in regex editors, but it doesn't work in PHP (no error). I thought by adding delimiters and running the pattern through preg_quote would address this. Would appreciate any help on what step I'm missing here.

Code sample:

$pattern = '%(?<=@address|.)singleline(?=[^\]\[]*\])%';  
$pattern = preg_quote($pattern);
$output  = preg_replace($pattern, "", $output);

HTML Sample:

  <p>[@address|singleline]</p>
  • 写回答

2条回答 默认 最新

  • doulezhi5326 2012-03-05 17:38
    关注

    preg_quote escapes characters that are regular expression syntax characters. These include . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -. Try not using preg_quote.

    $pattern = '%(?<=@address|.)singleline(?=[^\]\[]*\])%';  
    $output  = preg_replace($pattern, "", $output);
    

    EDIT: You might want to use preg_quote if you had content you wanted to include in your regex pattern which contained characters used in regex syntax. For example:

    $input = "item 1 -- total cost: $5.00";
    $pattern = "/total cost: " . preg_quote("$5.00") . "/";
    // $pattern should now be "/total cost: \$5.00/"
    $output = preg_replace($pattern, 'five dollars', $input);
    

    In this case, you need to escape the $ because it is used in the regex syntax. To search for it, your regex should use \$ instead of $. Using preg_quote performs this alteration for you.

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

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)