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;

出力:

マーニー・スタントンが最初にプロセスを案内してくれて、それからみんな夢中になった。

説明:

  • Modifiers is:i大文字と小文字を区別しない一致を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 に答える