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);
You can use this regex to capture all the square bracket contents:
(\[[^]]+\])
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);
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 ]
/(\[.*?\])/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.