1

I'm new to regular expressions and I checked the following pattern using RegExr, but it fails in PHP with preg_replace.

I've tried adding an extra backslash to escape the first \ with no luck.

Any help pointing me in the right direction would be greatly appreciated.

Example:

   $output = preg_replace("\[if](.*)[/if/]*", ' ', $output);

I've also tried adding slashes:

    $output = preg_replace("/\[if](.*)[/if/]*/", ' ', $output);

The string I'm trying to modify is:

[if] <p>A statement goes here</p> [/if]
3
  • Have you also tried enabling some error_reporting(~0)? Commented Mar 3, 2012 at 18:05
  • 1
    possible duplicate of PHP Regex for matching a UNC path - It might be insightful about what happens with those slashes in regular expression written in a PHP string. Most of these online tools don't give the PHP string, but just the regex. You need to encode it for PHP then in an extra step. Commented Mar 3, 2012 at 18:07
  • 1
    Please edit the question with a sample of the string you're trying to modify. I'm not sure if those square brackets are part of the regex logic or part of what you're trying to match. Commented Mar 3, 2012 at 18:15

1 Answer 1

3
  1. Escape all ['s and ]'s if you want it to mean a literal
  2. Delimiters are needed.
  3. If a delimiter occurs in a pattern, is must be esaped, or choose another delimiter (I chose % because of the /).
  4. The ending ]*, 0 or more times ].... are you sure?
  5. I suspect using an ungreedy (.*?) is more likely needed, but I leave that up to you.

Gives:

"%\[if\](.*)\[/if\]%"
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. This makes sense -- appreciate the explanation. I replaced it and no errors -- but the string wasn't replaced? I've added the string to the question.
The reason is that you need to remove the last / from the regex. It's trying to replace [if]whatever[/if/] there. Also, the last * can go too.
Working perfectly now. $output = preg_replace("%\[if\](.*?)\[/if\]%", '', $output);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.