jsuissa
jsuissa

Reputation: 1762

Working regex pattern doesn't work in PHP despite preg_quote

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>

Upvotes: 0

Views: 1211

Answers (2)

thetaiko
thetaiko

Reputation: 7834

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.

Upvotes: 2

a.tereschenkov
a.tereschenkov

Reputation: 807

I think you should apply preg_quote not for full pattern, bbut only for (maybe) external string. Look at this code:

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

    echo $output;

As you can see I apply preg_quote only for $content variable (that might be with some characters which You need to escape)

Upvotes: 1

Related Questions