使用正则表达式模式;尽管有preg_quote,但不能在PHP中工作


Working regex pattern doesn't work in PHP despite preg_quote

下面的模式似乎在regex编辑器中有效,但在PHP中不起作用(没有错误)。我认为通过添加分隔符并通过preg_quote运行模式可以解决这个问题。如果能帮上我的忙,我将不胜感激。

代码示例:

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

HTML示例:

  <p>[@address|singleline]</p>

preg_quote转义作为正则表达式语法字符的字符。其中包括CCD_ 2。尽量不要使用preg_quote

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

编辑:如果您有要包含在正则表达式模式中的内容,其中包含正则表达式语法中使用的字符,则可能需要使用preg_quote。例如:

$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);

在这种情况下,您需要转义$,因为它在regex语法中使用。要搜索它,正则表达式应该使用'$而不是$。使用preg_quote为您执行此更改。

我认为应该不为完整模式应用preg_quote,而仅为(可能)外部字符串应用bbut。看看这个代码:

<?php
    $content = 'singleline';
    $content = preg_quote($content);
    $output = '<p>[@address|singleline]</p>';
    $output  = preg_replace('%(?<=@address|.)'.$content.'(?=[^']'[]*'])%', "", $output);
    echo $output;

正如您所看到的,我只将preg_quote应用于$content变量(可能包含一些需要转义的字符)

相关文章: