改变宽度和高度的img标签结构

时间:2013-10-18 17:01:56

标签: php html readfile fwrite

我的网站中有一个编辑器会自动以这种格式保存图像:

<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字符串上运行任何函数。

感谢。

1 个答案:

答案 0 :(得分: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.'/>';
}