I am trying to remove some html from my string of text which comes from a Wordpress generated database.
I want this:
Marnie Stanton led us through the process first and then everyone went crazy.
[caption id="attachment_76" align="alignnone" width="191"] One of the work stations[/caption]
[caption id="attachment_78" align="alignnone" width="300"] The group is getting some great results[/caption]
[caption id="attachment_83" align="alignnone" width="224"] You can see the prints multiplying[/caption]
to turn into this:
Marnie Stanton led us through the process first and then everyone went crazy.
So what I want is everything from the first [caption]
to the very last [/caption]
to be removed.
I have started with this:
(\[caption\s+?[^]]+\])
Which only removes the first tag.
You may want to use something like this
$string = 'Marnie Stanton led us through the process first and then everyone went crazy.
[caption id="attachment_76" align="alignnone" width="191"] One of the work stations[/caption]
[caption id="attachment_78" align="alignnone" width="300"] The group is getting some great results[/caption]
I want to keep this !
[caption id="attachment_83" align="alignnone" width="224"] You can see the prints multiplying[/caption]';
$new_string = preg_replace('#\s*\[caption[^]]*\].*?\[/caption\]\s*#is', '', $string);
echo $new_string;
Output:
Marnie Stanton led us through the process first and then everyone went crazy.I want to keep this !
Explanation:
is
: i
means match case insensitive, s
means match new lines with dots .
\s*
: match white spaces 0 or more times\[caption
: match [caption
[^]]*
: match anything except ]
0 or more times\]
: match ]
.*?\[/caption\]
: match anything until [/caption]
found (and match [/caption]
)\s*
: match white spaces 0 or more timesOnline demo
As it seems you just want the start of the string, I would not use a regular expression but string functions:
$pos = stripos($your_string, '[caption');
$result = substr($your_string, 0, $pos);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With