Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading