2012-09-03 21 views
1

我有這個圖像標籤,我從一個天氣來源是有錯誤,輸出不是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但我似乎無法使其工作,任想法?

+2

您可以查看HTMLTidy或HTML Purifier等工具。他們是否會按照你期望的方式解析無效標籤,因爲它幾乎沒有定義如何解析HTML無效。 – deceze

+1

這是一個格式不正確的標籤。你能否提出一個算法來推斷哪些部分是相關的? –

+0

以及我需要刪除之間的一切

回答

1

此:

$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 />標記不會更改。

1

如果HTML始終具有完全相同的語法問題,則將刪除<imgsrc=之間的任何內容。這是很容易打破,如果HTML結構發生變化,但由於它已經破...

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

thanks, works flawless –

1

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

<?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; 
?> 
1

您可以嘗試以匹配您想從您的輸入保存的屬性,你可以嘗試讓看起來像一個<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"; 
} 
+1

the entire content is in one string so i cannot do this... –

+0

Updated with one more loop to extract the ''看部分第一 – complex857