4

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

3
  • expected output please? Commented Jul 7, 2015 at 14:40
  • Sorry, just simply 'Road'. I'll update question. Commented Jul 7, 2015 at 14:42
  • @Rizier123 i think he want to remain word inside (). rest he want to remove. Commented Jul 7, 2015 at 14:43

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

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.