Preg Replace in sub string leaving a part of the string remaining

I am using preg_replace

I am trying to replace everything between (and ideally including): [BW] and [/BW] with an empty string.

$string = MyText-[BW]field[/BW]-[COUNTER]0001[/COUNTER]-[D]YY/MM/DD[/D][BW]field_2[/BW]
$string = preg_replace('/'.preg_quote('[BW]').'[\s\S]+?'.'[\/BW]'.'/', '', $string); 

However the output I am getting seems to be keeping the follwing part: BW]

i.e. MyText-BW]-[COUNTER]0001[/COUNTER]-[D]YY/MM/DD[/D]BW]

The result I want is MyText--[COUNTER]0001[/COUNTER]-[D]YY/MM/DD[/D]

I have a workaround for this but i would prefer implement the function properly. What am I missing?

>Solution :

You forgot to preg_quote the latter portion of your search pattern. Fix that, and it works:

$string = MyText-[BW]field[/BW]-[COUNTER]0001[/COUNTER]-[D]YY/MM/DD[/D][BW]field_2[/BW]
$string = preg_replace('#'.preg_quote('[BW]').'[\s\S]+?'.preg_quote('[/BW]').'#', '', $string); 
echo $string;  // MyText--[COUNTER]0001[/COUNTER]-[D]YY/MM/DD[/D]

To avoid the issue with preg_quote() escaping backslash when used to escape the / delimiter, I have switched to using # as a delimiter.

Leave a Reply