Philip Badilla
Philip Badilla

Reputation: 1058

Match everything inside a parenthesis

I'm working on a regex in PHP that will match all inside a parenthesis, I'm having problem with special characters particullarly the ampersand(&)

If the string inside the parenthesis contains an ampersand it doesn't match.

Here is the sample string

_categories=true(test_asda=asd asdasd,asdawqe&hello=asdads)

Here is the expected output

test_asda=asd asdasd,asdawqe&hello=asdads

Here is the regex I'm currently using

/\(([^\&)]+)\)/

Upvotes: 1

Views: 90

Answers (2)

zx81
zx81

Reputation: 41838

Philip, this simple regex should do what you are trying to do.

$result = preg_replace('/_categories=true\(([^)]+)\)/', '\1', $subject);

Input: _categories=true(test_asda=asd asdasd,asdawqe&hello=asdads)

Output: test_asda=asd asdasd,asdawqe&hello=asdads

How does it work? Once we get inside the parentheses, we start capture group 1. What we are capturing is [^)]+ which means "any number of characters which are not a closing parenthesis", allowing you to consume the string up to the closing parenthesis )

Upvotes: 1

anubhava
anubhava

Reputation: 785058

Your regex should be:

/\(([^)]+)\)/

You're using [^\&)]+ which means match until you hit an ampersand OR right parentheses that's why it is stopping as soon as it is finding &

Upvotes: 3

Related Questions