编辑:
在我考虑了一秒钟之后,使用一大块示例 html 而不是一个漂亮的 img 标签列表来查看一个示例会更有帮助。请参阅下面的更新代码和输出。
规则非常简单,可以在需要时使用 preg_replace 轻松运行,并且可以使用 strpos 进行检查以保存正则表达式引擎调用。如果您有任何问题,请告诉我。
输出:
<html>
<head></head>
<body>
<p> LOLOLOLOLOLOLOL </p>
<img src="ex1.jpg" style="margin:5px 5px;float:left;" />
<p> LOLOLOLOLOLOLOL </p>
<img src="ex2.jpg" style="display:block;margin:5px auto;" />
<p> LOLOLOLOLOLOLOL </p>
<img src="ex3.jpg" style="display:block;margin-top:5px; margin-left:auto;" />
<p> LOLOLOLOLOLOLOL </p>
</body>
<html>
代码:
<?php
// sample html blob
$sample_html = '
<html>
<head></head>
<body>
<p> LOLOLOLOLOLOLOL </p>
<img src="ex1.jpg" style="margin:5px 5px;float:left;" />
<p> LOLOLOLOLOLOLOL </p>
<img src="ex2.jpg" style="margin:5px 175px;" />
<p> LOLOLOLOLOLOLOL </p>
<img src="ex3.jpg" style="margin-top:5px; margin-left:5px;" />
<p> LOLOLOLOLOLOLOL </p>
</body>
<html>';
// grab all the matches for img tags and exit if there aren't any
if(!preg_match_all('/<img.*\/>/i', $sample_html, $matches))
exit("Found no img tags that need fixing\n");
// check out all the image tags we found (stored in index 0)
print_r($matches);
// iterate through the results and run replaces where needed
foreach($matches[0] as $string){
// keep this for later so that we can replace the original with the fixed one
$original_string = $string;
// no need to invoke the regex engine if we can just do a quick search. so here
// we do nothing if it contains a float.
if(false !=- strpos($string, 'float:')){
continue;
}
// inject the display:block if it doesn't already exist
if(false === strpos($string, 'display:block;')){
$string = preg_replace('/(<img.*style=")(.* \/>)/i', '$1display:block;$2', $string);
}
// preg_replace only replaces stuff when it matches a pattern so it's safe to
// just run even if it wont do anything.
// replace margin left if in margin:vert horiz; form
$string = preg_replace('/(margin:[\s0-9]+px)\s[0-9]+px;/', "$1 auto;", $string);
// replace margin-left value to auto
$string = preg_replace('/(margin-left:).*;/', "$1auto;", $string);
// now replace the original occurence in the html with the fix
$sample_html = str_replace($original_string, $string, $sample_html);
}
// bam done
echo "{$sample_html}\n";
?>