2015-09-09 66 views
0

我有包含所有html元素的字符串,我必須除去圖像以外的所有東西。使用正則表達式從字符串中除去圖像標記除外

目前我使用此代碼

$e->outertext = "<p class='images'>".str_replace(' ', ' ', str_replace('Â','',preg_replace('/#.*?(<img.+?>).*?#is', '',$e)))."</p>"; 

其服務我的目的,但在執行速度很慢。任何其他方式來做同樣的事情將是可觀的。

+0

您的要求不明確。什麼是輸入和什麼是要求的輸出? –

+0

如何使用正則表達式刪除除圖像以外的所有內容@GilPeretz – santosh

+0

您的請求是從html文檔中除去圖像,但圖像的含義是什麼?圖片的標籤?圖像的路徑?圖片的名字?你還應該在你的問題中提供一個包含html元素的字符串的例子,以及你期望的字符串結果。 –

回答

0

您提供的代碼似乎無法正常工作,甚至正則表達式也不正確。你應該刪除像這樣的初始斜槓/#.*?(<img.+?>).*?#is

你的心態是去除一切,只留下圖像標籤,這不是一個好辦法。更好的方法是在捕獲所有圖像標籤後再使用匹配來構建輸出。首先我們來捕捉圖片標籤。可以使用此正則表達式來完成:

/<img.*>/Ug 

U標誌使正則表達式引擎變得懶惰,而不是渴望,所以它會匹配它找到的第一個>的遭遇。

DEMO1

現在,爲了構造輸出,讓我們使用的方法preg_match_all,並把結果在一個字符串。這可以用下面的代碼來完成:

<?php 
// defining the input 
$e = 
'<div class="topbar-links"><div class="gravatar-wrapper-24"> 
<img src="https://www.gravatar.com/avatar" alt="" width="24" height="24"  class="avatar-me js-avatar-me"> 
</div> 
</div> <img test2> <img test3> <img test4>'; 
// defining the regex 
$re = "/<img.*>/U"; 
// put all matches into $matches 
preg_match_all($re, $e, $matches); 
// start creating the result 
$result = "<p class='images'>"; 
// loop to get all the images 
for($i=0; $i<count($matches[0]); $i++) { 
    $result .= $matches[0][$i]; 
} 
// print the final result 
echo $result."</p>"; 

DEMO2

的另一種方法,以提高該代碼是使用函數編程(array_reduce例如)。但是我會把它當做家庭作業。

注意:還有另一種方法來實現這個解析html文檔並使用XPath來查找元素。檢查出this answer欲知更多信息。

+0

感謝@pedro的解釋。 – santosh

相關問題