2017-03-31 152 views
0

我正在重新制作一個WordPress插件,它指定了缺少width和/或height屬性的圖像尺寸。重印<img>具有所有屬性的標籤

正如您在我的current version on GitHub中看到的,我手動列出了<img>標記(L38)的所有屬性。但是,如果用戶要添加自定義屬性,它會得到忽略了,因爲它不是在我的$attributes變量中列出:

# Before 
<img src="http://example.com/img.png" class="img" data-sample="test"> 
# After 
<img src="http://example.com/img.png" class="img" width="100" height="30"> 

創建一個簡單的測試文件,我是能夠更新的正則表達式來存儲所有屬性在<img>標籤中找到。是的,我意識到使用DOMDocument的建議,但它在過去導致了更多的WordPress問題。

preg_match_all('/(?:<img|(?<!^)\G)\h*([-\w]+)="([^"]+)"(?=.*?\/>)/', $content, $images); 

爲了不填補這一職位有太多的代碼,我目前的工作測試文件on my GitHub Gist here

使用var_dump($images);,這給了我從我的樣本圖像輸出如下(我在每個數組的末尾添加...以節省空間):

0 => 
     array (size=19) 
     0 => string '<img src="https://placehold.it/250x100/99cc00/000.jpg?text=JPG"' (length=63) 
     1 => string ' alt="JPG"' (length=10) 
     2 => string '<img src="https://placehold.it/250x100.gif?text=GIF"' (length=52) 
     ... 
    1 => 
     array (size=19) 
     0 => string 'src' (length=3) 
     1 => string 'alt' (length=3) 
     2 => string 'src' (length=3) 
     ... 
    2 => 
     array (size=19) 
     0 => string 'https://placehold.it/250x100/99cc00/000.jpg?text=JPG' (length=52) 
     1 => string 'JPG' (length=3) 
     2 => string 'https://placehold.it/250x100.gif?text=GIF' (length=41) 
     ... 

我的目標是與所有的重建圖像標記計算維度後的屬性和值。從我的測試中,我嘗試以下,但它並沒有給我結果我期待:

foreach ($images[1] as $attributes[1] => $value) { 
    echo('< img ' . $value . '="' . 'value' . '" ><br>'); 
} 

回答

1

代碼:

$content = <<<EOT 
<p>List of sample images.</p> 
<img src="https://placehold.it/250x100/99cc00/000.jpg?text=JPG" alt="JPG" /><br> 
<img src="https://placehold.it/250x100.gif?text=GIF" alt="GIF" /><br> 
<img src="https://placehold.it/250x100/ff6600/000.png?text=PNG" alt="PNG" /><br> 
<img class="no-ext" src="https://placehold.it/350x150?text=No Extension" alt="No Ext" /><br> 
<img src="https://placehold.it/250x100.png" custom-attr="custom1" another-attr="custom2" /><br> 
<img class="svg" src="https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg" alt="SVG" /><br> 
<img class="webp" src="https://gstatic.com/webp/gallery/1.webp" width="100" alt="webP" /><br> 
EOT; 
# Find all content with <img> tags 
preg_match_all('/(?:<img|(?<!^)\G)\h*([-\w]+)="([^"]+)"(?=.*?\/>)/', $content, $images); 
foreach ($images[1] as $attributes[1] => $value) { 
    echo('< img ' . $value . '="' . 'value' . '" ><br>'); 
} 

解決方案:

//echo "<pre>"; print_r($images); 
$temp = array(); 
foreach($images[0] as $key=>$img){  
    $pos = strpos($img,'<img'); 
    if($pos === false){ 
     $temp[$key_2][] = $img; 
    }else{ 
     $temp[$key][] = $img; 
     $key_2 = $key; 
    } 
} 
foreach($temp as $k=>$v){ 
    $str[] = implode(' ', $v) . ' />'; 
} 

$finalStr = implode('<br />', $str); 

echo $finalStr; 

Click here to check output

相關問題