1

我在 WP 中有字幕,我需要从中提取文本。

最初,它们看起来像这样:

[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 id="attachment_16689" align="aligncenter" width="754"] I want to get this text out of here.[/caption]

我希望能够从标题中取出文本,留下“我想把这段文字从这里取出。”。我尝试了许多不同的表达方式,但没有一个可以开始工作。在上面的代码之后,我有:

preg_replace('/(\[caption.*])(.*)(\[/caption\])/', '$1$3', $c);

我究竟做错了什么?

4

2 回答 2

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);
$c = preg_replace('%(\\[caption.*])(.*)(\\[/caption\\])%', '$2', $c);

您还可以通过将标题替换添加到数组中来进一步缩小它。只要确保第二个参数也是一个数组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);
于 2012-11-27T19:51:22.587 回答
1
$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;
于 2012-11-27T19:43:54.433 回答