预替换图像宽度、高度和样式
preg-replace image width, height and style
我的图片是这样的:
<img alt="" width="146" height="109" src="http://url.to/src.jpg" style="float:left" />
但我不知道如何用 preg_replace 或 preg_replace_callback 来实现它:
<img alt="" src="http://url.to/src.jpg" style="width:146;height:109;float:left">
这适用于高度和宽度,但我无法添加样式元素 "float:left"
$html='<img alt="" width="146" height="109" src="http://url.to/src.jpg" style="float:left" />';
$pattern = ('/<img[^>]*width="(\d+)"\s+height="(\d+)">/');
preg_match($pattern, $html, $matches);
$style = "<img style=\"width:".$matches[1]."px; height:".$matches[2]."px;\"";
$html = preg_replace($pattern, $style, $html);
这将是
<img alt="" style="width:146;height:109" src="http://url.to/src.jpg" style="float:left">
由于双重样式元素而无法正常工作
试试下面的正则表达式
<?php
$html='<img alt="" width="146" height="109" src="http://placehold.it/140x200" style="float:left" />';
$pattern = '/(<img.*)width="(\d+)" height="(\d+)"(.*style=")(.*)" \/(>)/';
$style = 'width:px;height:px;';
$html = preg_replace($pattern, $style, $html);
echo $html; //view source of page to see the code change
?>
请注意使用方括号 '(' ')' 创建匹配的组,稍后可以使用 $1 $2 等引用这些组。转到 regex101.com 并尝试正则表达式。
以上代码将导致以下结果,除了最后一部分,这应该无关紧要,但您可以进一步修改它。
<img alt="" src="http://placehold.it/140x200" style="width:146;height:109;float:left" />
我的图片是这样的:
<img alt="" width="146" height="109" src="http://url.to/src.jpg" style="float:left" />
但我不知道如何用 preg_replace 或 preg_replace_callback 来实现它:
<img alt="" src="http://url.to/src.jpg" style="width:146;height:109;float:left">
这适用于高度和宽度,但我无法添加样式元素 "float:left"
$html='<img alt="" width="146" height="109" src="http://url.to/src.jpg" style="float:left" />';
$pattern = ('/<img[^>]*width="(\d+)"\s+height="(\d+)">/');
preg_match($pattern, $html, $matches);
$style = "<img style=\"width:".$matches[1]."px; height:".$matches[2]."px;\"";
$html = preg_replace($pattern, $style, $html);
这将是
<img alt="" style="width:146;height:109" src="http://url.to/src.jpg" style="float:left">
由于双重样式元素而无法正常工作
试试下面的正则表达式
<?php
$html='<img alt="" width="146" height="109" src="http://placehold.it/140x200" style="float:left" />';
$pattern = '/(<img.*)width="(\d+)" height="(\d+)"(.*style=")(.*)" \/(>)/';
$style = 'width:px;height:px;';
$html = preg_replace($pattern, $style, $html);
echo $html; //view source of page to see the code change
?>
请注意使用方括号 '(' ')' 创建匹配的组,稍后可以使用 $1 $2 等引用这些组。转到 regex101.com 并尝试正则表达式。
以上代码将导致以下结果,除了最后一部分,这应该无关紧要,但您可以进一步修改它。
<img alt="" src="http://placehold.it/140x200" style="width:146;height:109;float:left" />