2013-10-18 122 views
0

我在我的網站編輯會自動這種格式保存圖像:變化img標籤結構

<img alt="image-alt" src="image-path" style="width: Xpx; height: Ypx;" title="image-title" /> 

這個標籤將在靜態.html文件保存,然後會顯示在我的網站與ReadFile的()... 我想在靜態HTML文件保存它這種新的格式之前,要改變這種結構:

<img alt="image-alt" src="image-path" width="Xpx" height="Ypx" title="image-title" /> 

逸岸,我想改變的方式「寬度」和「高度」在靜態HTML文件中寫入。

我使用PHP並可以在fwrite()之前在html字符串上運行任何函數。

謝謝。

+0

您將需要更改代碼生成功能,在編輯器中,或者如果輸出總是同上,你可以使用str_replace()函數,但我猜X和Y只是佔位符,編輯正在把價值放在那裏?如果是這樣,你可能需要使用一些正則表達式來取代它。 – Mattt

回答

0

我開始時認爲這很容易使用preg_replace_callback,但它變成了一個怪物。我敢肯定,它可以很容易地用一點重構的改善:

<?php 
// Some HTML test data with two images. For one image I've thrown in some extra styles, just 
// to complicate things 
$content= '<img alt="image-alt-2" src="image-path" style="width: 20px; height: 15px; border: 1px solid red;" title="image-title" /> 
    <p>Some other tags. These shouldn\'t be changed<br />Etc.</p> 
<img alt="image-alt-2" src="image-path-2" style="width: 35px; height: 30px;" title="another-image-title" /> 
<p>This last image only has a width and no height</p> 
<img alt="image-alt-3" src="image-path-3" style="width:35px;" title="another-image-title" />'; 

$content= preg_replace_callback('/<img ((?:[a-z]+="[^"]*"\s*)+)\/>/i', 'replaceWidthHeight', $content); 

var_dump($content); 

function replaceWidthHeight($matches) { 
    // matches[0] will contain all the image attributes, need to split 
    // those out so we can loop through them 
    $submatches= array(); 
    $count= preg_match_all('/\s*([a-z]+)="([^"]*)"/i', $matches[1], $submatches, PREG_SET_ORDER); 

    $result= '<img '; 

    for($ndx=0;$ndx<sizeof($submatches);$ndx++) { 
     if ($submatches[$ndx][1]=='style') { 
      // Found the style tag ... 
      $width= ''; // Temporary storage for width and height if we find them 
      $height= ''; 

      $result.= ' style="'; 
      $styles= split(';', $submatches[$ndx][2]); 
      foreach($styles as $style) { 
       $style= trim($style); // remove unwanted spaces 

       if (strlen($style)>6 && substr($style, 0, 6)=='width:') { 
        $width= trim(substr($style, 6)); 
       } 
       elseif (strlen($style)>7 && substr($style, 0, 7)=='height:') { 
        $height= trim(substr($style, 7)); 
       } 
       else { // Some other style - pass it through 
        $result.= $style; 
       } 
      } 
      $result.= '"'; 
      if (!empty($width)) $result.= " width=\"$width\""; 
      if (!empty($height)) $result.= " height=\"$height\""; 
     } 
     else { 
      // Something else, just pass it through 
      $result.= $submatches[$ndx][0]; 
     } 
    } 

    return $result.'/>'; 
}