2013-07-11 39 views
1

HTML代碼與用戶定義的標籤使用preg_match_all圖像源

<img src="http://website/image/ngshjk.jpeg" onload="img_onload(this);" onerror="img_onerror(this);" data-pid="dynamicvalue" data-imagesize="ppew" data-error-url="http://img.comb/6/z2default.jpg" class="small_image imageZoom " alt="image" title="" id="visible-image-small" rel="dynamicvalue" data-zoom-src="http://img.comb/6/z21347.jpeg" style="display: inline;"> 

PHP代碼

preg_match_all('/<img(.*) onload="(.*)" \/s',$con,$val); 

而在這頁有這麼多的img標籤。所以我試圖使用img標籤中的一些屬性來獲取特定圖像的src。我在preg_match_all中無法正確。請糾正我在獲取上述img標籤中的源代碼。

+0

這個所需的圖像標記與所有其他圖像標記有何不同? –

+0

@Denomales這就是爲什麼我無法做到。我敢肯定其他img標籤沒有onload =「img_onload(this);」 –

+0

最好是在你的代碼中簡單地找到所有的圖像標籤作爲列表,然後在你的代碼中簡單地檢查它們以找到有趣的那些? –

回答

3

用懶惰.*?代替貪婪.*可能會更好。

preg_match_all('/<img(.*?)\sonload="([^"]*)"/s',$con,$val); 

並更改第二.*[^"]*代替。

.*?,直到下一個匹配數最少的字符相匹配(在這種情況下onload...)和[^"]*匹配在引號之間的任何非引號字符。

+0

沒有改進..加載整個頁面:( –

+0

@MohamedFawaskhan你是否也想獲得src屬性?如果是這樣,你可以使用' Jerry

0

說明

這個表達式將:

  • 驗證圖像標籤具有的data-imagesize="ppew"
  • 屬性/值驗證所述圖像標籤具有data-pid="ABCDEFGHIJ"
  • 捕獲src屬性值的屬性/值
  • 避免潛在的難題

<img\b(?=\s) # capture the open tag 
(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?\sdata-imagesize="ppew") # validate data-imagesize exists with a specific value 
(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?\sdata-pid="ABCDEFGHIJ") # validate data-pid exists with a specific value 
(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?\ssrc=['"]([^"]*)['"]?) # capture the src attribute value 
(?:[^>=]|='[^']*'|="[^"]*"|=[^'"\s]*)*"\s?\/?> # get the entire tag 

enter image description here

例子

活生生的例子:http://www.rubular.com/r/PBJ50cax7L

單線正則表達式:<img\b(?=\s)(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?\sdata-imagesize="ppew")(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?\sdata-pid="ABCDEFGHIJ")(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?\ssrc=['"]([^"]*)['"]?)(?:[^>=]|='[^']*'|="[^"]*"|=[^'"\s]*)*"\s?\/?>

示例文字

注意第一行有一些潛在問題的條件

<img onmouseover=' data-imagesize="ppew" ; data-pid="ABCDEFGHIJ" ; funSwap(data-imagesize, data-pid) ; ' src="http://website/NotTheDroidYourLookingFor.jpeg" onload="img_onload(this);" onerror="img_onerror(this);" data-pid="jihgfedcba" data-imagesize="ppew" /> 
<img src="http://website/someurl.jpeg" onload="img_onload(this);" onerror="img_onerror(this);" data-pid="ABCDEFGHIJ" data-imagesize="ppew" /> 

捕捉組

[0] = <img src="http://website/someurl.jpeg" onload="img_onload(this);" onerror="img_onerror(this);" data-pid="ABCDEFGHIJ" data-imagesize="ppew" /> 
[1] = http://website/someurl.jpeg 
+0

我在創建表達方面很弱,但我可以理解你的代碼。我編輯我的問題,請現在看看。 –

0

要得到網頁上的所有圖像標籤,它可能會更容易使用像一個HTML解析工具:

// load your html string 
$dom = new DOMDocument(); 
$dom->loadHTML($your_html_here); 


// find all the img tags 
$imgs = $dom->getElementsByTagName('img'); 

// cycle through all image tags 
foreach($imgs as $img) { 
    $src = $img->getAttribute("src"); 
    // do something 
}