簡體   English   中英

整理圖像標簽

[英]Tidy up an image tag

我有這個圖像標簽,我從一個有錯誤的天氣來源,輸出不是HTML但wml / wap所以當它出現時它崩潰和灼傷。 圖片標簽出現如下:

<img alt="FACE="Monospace,Courier">LRPatches, Sky clear, Q1020</FONT><Mist, >" src="http://www.vremea.com/images/fogshow.gif"  width="50" height="50"/>

我希望它是這樣的:

<img src="http://www.vremea.com/images/fogshow.gif"  width="50" height="50"/>

我知道我必須使用preg_replace但我似乎無法讓它工作,任何想法?

如果HTML總是具有完全相同的語法問題,那么這將刪除<imgsrc=之間的任何內容。 如果HTML結構發生變化,這很容易破解,但因為它已經破碎了......

$html = preg_replace('/(?<=<img ).*?(?=src=)/', '', $horribleHorribleHTML);

它沒有經過測試,但應該這樣做。

<?php
$sStr = '<img ... your image>'; // your string
$iStart = strpos('src="', $sStr); // find the src
$iEnd = strpos('"', $sStr, $iStart); // find the end
$sURL = substr($sStr, $iStart, $iEnd); // get the image
echo $sURL;
?>

您可以嘗試匹配要從輸入中保存的屬性,您可以嘗試首先獲取看起來像<img>標記的部分,然后挑選屬性,查看您感興趣的部分:

$input = 'some other content
    <img alt="FACE="Monospace,Courier">LRPatches, Sky clear, Q1020</FONT><Mist, >"
        src="http://www.vremea.com/images/fogshow.gif"  width="50" height="50"/>
        <span class="some"> more other content
    </span>

    <img alt="FACE="Monospace,Courier">LRPatches, Sky clear, Q1020</FONT><Mist, >"
        src="http://www.vremea.com/images/fogshow.gif"
        width="50"
        height="50"/> <span class="some"> more other content
    ';
preg_match_all('/<img.+?\/>/sim', $input, $img_parts);
foreach ($img_parts[0] as $img_part) {
    $attrs = array();
    preg_match_all('/(?<key>src|width|height)\s*=\s*"(?<value>[^"]+)/i', $img_part, $m);
    foreach ($m['key'] as $i => $key) {
        $attrs[] = "{$key}=\"{$m['value'][$i]}\"";
    }
    print "<img ".join(' ', $attrs)." />\n";
}

這個 :

$imgTag = '<img alt="FACE="Monospace,Courier">LRPatches, Sky clear, Q1020</FONT><Mist, >" src="http://www.vremea.com/images/fogshow.gif"  width="50" height="50"/>';
$returnValue = preg_replace('/(<img)(.*)(src.*)/', '$1 $3',$imgTag);

將輸出:

'<img src="http://www.vremea.com/images/fogshow.gif"  width="50" height="50"/>'

假設您的格式錯誤的<img />標記沒有改變。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM