1

キャプションタグ内のimgタグを取得したい

例:

[caption id="attachment_5433" align="aligncenter" width="413"]
    <a href="abc.jpg"><img class=" wp-image-5433" title="This is a title" src="abc.jpg" alt="This is alt" width="413" height="551"></a>This is a desc
[/caption]

そして結果:

<img class=" wp-image-5433" title="This is a title" src="abc.jpg" alt="This is alt" width="413" height="551">

PHP正規表現でそれを行う方法は?

4

2 に答える 2

0
<?php
    $string = '[caption id="attachment_5433" align="aligncenter" width="413"]
    <a href="abc.jpg"><img class=" wp-image-5433" title="This is a title" src="abc.jpg" alt="This is alt" width="413" height="551"></a>This is a desc
[/caption]';

    $result = preg_match_all("/\[caption.*?].*?(<img.*?\/?>).*?\[\/caption]/s", $string, $matches);

    print_r($matches);
?>

出力

Array
(
    [0] : Array
        (
            [0] : '[caption id="attachment_5433" align="aligncenter" width="413"]
    <a href="abc.jpg"><img class=" wp-image-5433" title="This is a title" src="abc.jpg" alt="This is alt" width="413" height="551"></a>This is a desc
[/caption]'
        )

    [1] : Array
        (
            [0] : '<img class=" wp-image-5433" title="This is a title" src="abc.jpg" alt="This is alt" width="413" height="551">'
        )

)

更新、replace コールバックあり

<?php
    $string = '[caption id="attachment_5433" align="aligncenter" width="413"]
    <a href="abc.jpg"><img class=" wp-image-5433" title="This is a title" src="abc.jpg" alt="This is alt" width="413" height="551"></a>This is a desc
[/caption]';

    echo preg_replace_callback('/\[caption.*?].*?(<img.*?\/?>).*?\[\/caption]/s', function($matches) {
        return $matches[1];
    }, $string);
?>
于 2013-04-18T09:49:56.503 に答える
0
preg_match_all('/\[caption.*?\].*?(\<img[^>]*?).*?\[\/caption\]/', $stringWhereToSearchImg, $matches);

マッチには img タグが付きます。

ちなみに、img の場合は /> で終了する必要があります。

于 2013-04-18T09:36:40.273 に答える