/    Sign up×
Community /Pin to ProfileBookmark

Escaping braces in PCRE

I am trying to use curly braces in a custom markup, using preg_replace to convert them into the final HTML, but I keep getting rewarded with error messages.

The basic search string I’m working with is /{{(.+?)}}{/ which should match any string of the format “{{foo}}{“. Deleting the final two braces allows it to match “{{foo}}” just fine, otherwise I am told:

Parse error: syntax error, unexpected ‘}’

I therefore conclude that PCRE thinks I’m trying to start a quantifier, and I wouldn’t blame it, except it gives exactly the same error if I escape { with . It also gives the same error if I go nuts and try escaping { with . Going all out and attempting to escape { with finally stops the error message, but it won’t match “{{foo}}{“.

Any help with this will be fantastically appreciated. I’ve been working on this preg_replace array for days, and I don’t think there’s any part of it that hasn’t caused my consternation. Thank you in advance!

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@NogDogAug 13.2008 — You can manually escape them with backslashes:
[code=php]
$regexp = '/{{(.+?)}}/';
[/code]

A possible alternative (probably not needed here but possibly useful in other circumstances) is the preg_quote() function:
[code=php]
$regexp = '/' . preg_quote('{{'} . '(.+?)' . preg_quote('}}') . '/';
[/code]
×

Success!

Help @Labyns spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.5,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...