2017-03-31 111 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

相关问题