Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression remove [caption]

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.

like image 669
Dylan Cross Avatar asked Dec 27 '22 02:12

Dylan Cross


2 Answers

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:

  • Modifiers 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 times

Online demo

like image 56
HamZa Avatar answered Dec 28 '22 14:12

HamZa


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);
like image 24
jeroen Avatar answered Dec 28 '22 15:12

jeroen