tags:

views:

55

answers:

2

Hi,

I am trying to remove following tag from string.

[caption id="attachment_9" align="alignleft" width="137" caption="test"][/caption]

How do I remove it using php's preg_replace?

I tried serveral regular expression, but failed all.

Please advise me.

Thanks.

+4  A: 
$output_string = preg_replace('#\[caption[^\]]*\](.*?)\[/caption\]#m", "$1", $input_string)

or if you also want to remove anything between the opening and closing tag, just change "$1" to "".

Amber
A: 

Here you are:

Tested here: http://www.pagecolumn.com/tool/pregtest.htm

<?php 
$ptn = "/\[caption.+caption\]/";
$str = "Otherstuff[caption id=\"attachment_9\" align=\"alignleft\" width=\"137\" caption=\"test\"][/caption]Something else";
$rpltxt = "@";
echo preg_replace($ptn, $rpltxt, $str);
?>
Michael
-1 Two major problems with this. 1. Fails because you don't check for greedy conditions. "hello[caption][/caption]NOT IN A CAPTION[caption][/caption]world" will get replaced "helloworld". 2. This doesn't accommodate for caption sets that span multiple lines. Will fail for "[caption]\n[/caption]". As another note, you have an unescaped " inside $str, meaning that code won't even run.
Jamie Wong
I corrected item 2. An oversight while quickly posting the generated code from that link. Regarding item 1, you are absolutely right. His question did not provide much context and I found a quick solution. Amber has the better solution.
Michael