0

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

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

谢谢。

4

1 回答 1

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.'/>';
}
于 2013-10-18T18:47:01.927 回答