Reputation: 1891
I have captions in WP that I need to grab the text out of.
Initially, they look like this:
[caption id="attachment_16689" align="aligncenter" width="754"]<a href="http://www.site.com/" target="_blank"><img class=" wp-image-16689 " title="Title" src="http://site.com/wp-content/uploads/2012/11/image.jpg" alt="" width="754" height="960" /></a> I want to get this text out of here.[/caption]
I'm able to strip out the image and a tag with:
$c = preg_replace(array("/<img[^>]+\>/i", "/<a[^>]*>(.*)<\/a>/iU"), "", $caption);
Which leaves:
[caption id="attachment_16689" align="aligncenter" width="754"] I want to get this text out of here.[/caption]
I want to be able to get the text out of the caption leaving "I want to get this text out of here.". I have tried a number of different expressions, none of which I can get to work. After the above code I have:
preg_replace('/(\[caption.*])(.*)(\[/caption\])/', '$1$3', $c);
What am I doing wrong?
Upvotes: 1
Views: 1484
Reputation: 961
See below, you actually want to replace with the 2nd subject. Also, you had some mis-escaped backslashes.
$caption = '[caption id="attachment_16689" align="aligncenter" width="754"]<a href="http://www.site.com/" target="_blank"><img class=" wp-image-16689 " title="Title" src="http://site.com/wp-content/uploads/2012/11/image.jpg" alt="" width="754" height="960" /></a> I want to get this text out of here.[/caption]';
$c = preg_replace(array("/<img[^>]+\>/i", "/<a[^>]*>(.*)<\/a>/iU"), "", $caption);
$c = preg_replace('%(\\[caption.*])(.*)(\\[/caption\\])%', '$2', $c);
You could also skinny it down a little more by adding the caption replace into the array. Just make sure the second argument is an array as well array('','','$2')
$caption = '[caption id="attachment_16689" align="aligncenter" width="754"]<a href="http://www.site.com/" target="_blank"><img class=" wp-image-16689 " title="Title" src="http://site.com/wp-content/uploads/2012/11/image.jpg" alt="" width="754" height="960" /></a> I want to get this text out of here.[/caption]';
$c = preg_replace(array("/<img[^>]+\>/i", "/<a[^>]*>(.*)<\/a>/iU",'%(\\[caption.*])(.*)(\\[/caption\\])%'), array('','','$2'), $caption);
Upvotes: 3
Reputation: 16828
$string = '[caption id="attachment_16689" align="aligncenter" width="754"] I want to get this text out of here.[/caption]';
preg_match("/\[caption.*\](.*?)\[\/caption\]/",$string,$matches);
$caption_text = $matches[1];
echo $caption_text;
Upvotes: 1