John the Painter
John the Painter

Reputation: 2615

PHP preg_replace string – contents within brackets

I'm struggling to understand PHP preg_replace and wondered if you could offer any guidance on how to work out how to keep the word within the brackets but remove everything else from this string:

Events (Road)

So it would return:

Road

I'm keen to learn so don't just need the answer but need to understand how it's possible.

I know how to remove the words within the brackets (and the brackets) with:

trim(preg_replace('/\s*\([^)]*\)/', '', 'Events (Road)')

Cheers, R

Upvotes: 4

Views: 1699

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78984

One way is to capture the characters within the parentheses and then replace everything else with that. $1 is a back-reference to the first capture group ():

preg_replace('/.*\(([^)]*)\)/', '$1', 'Events (Road)');

Regular expression visualization

Debuggex Demo

Upvotes: 3

Related Questions