views:

45

answers:

4

Hi there,

If I have a string that looks like my name is {your name here} and I am from {country}. I am trying to use preg_replace to remove the {content} so the string ends up as my name is and I am from .

But I can not work out the regex for the pattern.

Can someone please help me out?


my name is and I am from . is simply a sample string.

it could be something like the current date is {current date} in {suburb}

+4  A: 

Perhaps something like:

/\{[^{}]*}/

Untested, but should get you started. First you match the {, then everything except }, and then the final }.

edit: fixed it, and now it's actually tested ;)

Evert
+1, but a) you can remove the backslash inside the character class (and before a closing brace in general), b) you don't need the parentheses, and c) you might want to add the opening brace there, too. This makes sure that the regex will fail completely on nested tags instead of matching `{tag 1 {tag 2}` and leaving `rest of tag 1}` unmatched. `/\{[^{}]*}/` is just as good.
Tim Pietzcker
Great suggestions tim
Evert
A: 

You can try:

\{.*?}
tinifni
A: 

For your "toolbox": there are online regular expression checkers, such as this one. It provides a good testbed since it is completely separate from your code.

+1 Evert -- you solution looks good.

zourtney
+1  A: 
$str = 'my name is {your name here} and I am from {country}.';
echo preg_replace('/{.*?}/', '', $str),"\n";

output:

my name is  and I am from .
M42