1

私はhtmlコンテンツを読んでいます。のような画像タグがあります。

<img onclick="document.location='http://abc.com'" src="http://a.com/e.jpg" onload="javascript:if(this.width>250) this.width=250">

また

<img src="http://a.com/e.jpg" onclick="document.location='http://abc.com'" onload="javascript:if(this.width>250) this.width=250" />

このタグを次のように再フォーマットしようとしました

<img src="http://a.com/e.jpg" />

しかし、私は成功していません。これまでに構築しようとしたコードは次のようなものです

$image=preg_replace('/<img(.*?)(\/)?>/','',$image);

誰でも助けることができますか?

4

2 に答える 2

1

<img>これは、属性を除くすべての属性をタグから削除する DOMDocument を使用したバージョンsrcです。loadHTMLDOMDocument でandsaveHTMLを実行すると、特にその html の形式が正しくない場合に、他の html も変更される可能性があることに注意してください。したがって、注意してください - 結果が受け入れられるかどうかをテストして確認してください。

<?php

$html = <<<ENDHTML
<!doctype html>
<html><body>
<a href="#"><img onclick="..." src="http://a.com/e.jpg" onload="..."></a>

<div><p>
<img src="http://a.com/e.jpg" onclick="..." onload="..." />
</p></div>
</body></html>
ENDHTML;

$dom = new DOMDocument;
if (!$dom->loadHTML($html)) {
    throw new Exception('could not load html');
}

$xpath = new DOMXPath($dom);

foreach ($xpath->query('//img') as $img) {
    // unfortunately, cannot removeAttribute() directly inside
    // the loop, as this breaks the attributes iterator.
    $remove = array();
    foreach ($img->attributes as $attr) {
        if (strcasecmp($attr->name, 'src') != 0) {
            $remove[] = $attr->name;
        }
    }

    foreach ($remove as $attr) {
        $img->removeAttribute($attr);
    }
}

echo $dom->saveHTML();
于 2013-07-24T12:15:06.073 に答える
0

一度に1つずつ一致させてから文字列を連結します。使用している言語がわからないので、擬似的に説明します。

1.Find <img with regex place match in a string variable
2.Find src="..." with src=".*?" place match in a string variable
3.Find the end /> with \/> place match in a string variable
4.Concat the variables together
于 2013-07-24T11:12:29.943 に答える