4

我正在尝试从来自 Wordpress 生成的数据库的文本字符串中删除一些 html。

我要这个:

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]  

变成这样:

Marnie Stanton led us through the process first and then everyone went crazy. 

所以我想要的是从第一个[caption]到最后一个[/caption]被删除的所有内容。

我从这个开始:

(\[caption\s+?[^]]+\])

仅删除第一个标签。

4

4 回答 4

9

你可能想使用这样的东西

$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;

输出:

Marnie Stanton 首先带领我们完成了整个过程,然后每个人都发疯了。我想保留这个!

解释:

  • 修饰符isi表示不区分大小写,s表示用点匹配新行.
  • \s*: 匹配空格 0 次或多次
  • \[caption: 匹配[caption
  • [^]]*: 匹配除]0 次或多次以外的任何内容
  • \]: 匹配]
  • .*?\[/caption\]: 匹配任何东西直到[/caption]找到(和匹配[/caption]
  • \s*: 匹配空格 0 次或多次

在线演示

于 2013-06-07T15:59:23.110 回答
1

看起来你只想要字符串的开头,我不会使用正则表达式,而是使用字符串函数:

$pos = stripos($your_string, '[caption');
$result = substr($your_string, 0, $pos);
于 2013-06-07T15:55:11.927 回答
1

[标题] 是一个简码示例。您可以使用 Wordpress 的strip_shortcodes();功能删除所有简码。

$text = '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]';

$text = strip_shortcodes($text);
echo $text;

这将输出:

Marnie Stanton 首先带领我们完成了整个过程,然后每个人都发疯了。我想保留这个!


[说明] 文档

strip_shortcodes 文档

于 2016-02-18T00:51:26.640 回答
0

似乎你可以用换行符来爆炸字符串,然后只取第一行......

<?php

$str = <<<EOD
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]
EOD;

$lines = explode("\n", trim($str));

echo $lines[0]; # Marnie Stanton led us through the process first and then everyone went crazy.
于 2013-06-07T16:04:17.803 回答