1

how do i explode the square brackets and then replace them with some text?

i tried the following code, but it seems only recognize the first two:

Regex code:

/(\[[\w\s]+\])/g

anyone can suggest what needs to be changed in the regex code?

$data = "[Foo Bar],[Suganthan],['Test1',1,5.09,12.50, 7.41]";

but it only finds: [Foo Bar],[Suganthan]

preg_replace('/(\[[\w\s]+\])/', 'replaced', $data);

3 Answers 3

5

That is because you're limiting the matchable characters in character class. [\w\s]+ only matchs all alphanumericals and spaces and underscore.

Use [^]]+

which means match anything except ]

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

Comments

3
/(\[.*?\])/g

You can try this.Your regex will not match ['Test1',1,5.09,12.50, 7.41] this wont match as it has , and ' which are not convered by \w\s

Or simply use

(\[[\w\s',.]+\])

See demo.

https://regex101.com/r/rU8yP6/23

Comments

2

You can use this regex to capture all the square bracket contents:

(\[[^]]+\])

RegEx Demo

Code:

$data = preg_replace('/\[[^]]+\]/', 'replaced', $data);

If you only want to find content from inside the [ and ] then use lookarounds as in this regex:

(?<=\[)[^]]+(?=\])

And use code as:

$data = preg_replace('/(?<=\[)[^]]+(?=\])/', 'replaced', $data);

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.