2011-03-28 53 views
2

可以說一位會員發表評論。PHP:過濾來自MY網站的除腳本和圖像以外的所有代碼?

Hi! Look at these cars. 
<img src="http://www.mysite.com/possiblefolder/possiblesub/image.jpg"></img> 
<img src="http://othersite.com/possiblefolder/possiblesub/image.jpg"></img> 
<img src="http://www.mysite.otherside.com/possiblefolder/image.jpg"></img> 
Which is your favorite? 

我想要的結果上來如:

Hi! Look at these cars. 
<img src="http://www.mysite.com/possiblefolder/possiblesub/image.jpg"></img> 
http://othersite.com/possiblefolder/possiblesub/image.jpg 
http://www.mysite.otherside.com/possiblefolder/possiblesub/image.jpg 
Which is your favorite? 

我要過濾除圖像和腳本從我的網站未來的所有代碼。任何人有任何想法?

+0

怎麼了與' 2011-03-28 08:02:37

+0

I want ' Darius 2011-03-28 08:05:02

回答

1

希望這有助於

<(\w+).+src=[\x22|'](?![^\x22']+mysite\.com[^\x22']+)([^\x22']+)[\x22|'].*>(?:</\1>)? 

第1組中使用的標籤和組2是「src」值,因此您可以進行替換。

In Browser Demo

enter image description here

+1

Absolutely BEAUTIFUL! Thank you! – Darius 2011-03-29 23:42:07

+0

I'm having some issues, it looked like it worked on your site but once I tried it in php it didn't work. – Darius 2011-04-04 13:15:34

+0

preg_replace(<(\w+).+src=[\x22|'](?![^\x22']+mysite\.com[^\x22']+)([^\x22']+)[\x22|'].*>(?:)? ,$ 2,$ message);應該正確嗎?但事實並非如此,它是否適合你? – Darius 2011-04-04 13:16:10

0

您可以使用PHP用strip_tags()從用戶評論(強烈推薦),還需要執行一些腳本代碼,如BB代碼的phpBB論壇等去除所有的HTML標記出來......

[img]possibleimgdir/someimage.jpg[/img] 

稍後搜索[img]和[/ img],在標籤之間找到的內容前追加根URL(例如http://www.mysite.com/possibleimgdir/someimage.jpg),檢查文件是否存在,然後爲該SRC屬性創建HTML IMG標籤(如果該標籤有效)。 ..

這只是一個可能的想法!

+0

Thought about this method, but I wanted to stick to using Darius 2011-03-28 08:15:25

+0

I did not realize that you want to filter out code people copied from clipboard. Well then, I suggest preg_replace()... – Wh1T3h4Ck5 2011-03-28 08:47:30

1

在最合理的情況下,特別是在你的例子,這將工作:

$new_comment = preg_replace('%<img.*?\ssrc="(http://(?!www.mysite.com).*?)".*?>.*?</img>%', '\1', $old_comment); 

它會給你所描述的結果。

0

你可以用一個jQuery oneliner做到這一點:

$('img:not(src^="http://www.mysite.com/")').hide() 
1

如果不是正確的XHTML,通過整潔運行它。如果是已經乾淨了XHTML,跳過這一部分

$config = array('output-xhtml' => true); 
$tidy = new tidy(); 
$html = $tidy->repareString($html, $config, 'utf8'); 

現在,有乾淨的XHTML可以使用XPath:

$xhtml = new SimpleXMLElement($html); 
foreach ($xhtml->xpath('//*/img') as $img_parent) { 
    if(!(strpos($img_parent->img->src, 'http://www.mysite.com/') === 0)) { 
    $img_parent->img = new SimpleXMLElement($img_parent->img->src); 
    } 
} 
$cleaned_html = $xhtml->asXML(); 
相關問題