简体   繁体   English

预浸料的图像宽度,高度和样式

[英]preg-replace image width, height and style

My image looks like this: 我的图像如下所示:

<img alt="" width="146" height="109" src="http://url.to/src.jpg" style="float:left" />

but i can't figure out how to bring it with preg_replace or preg_replace_callback to this: 但我不知道如何将其与preg_replace或preg_replace_callback一起使用:

<img alt="" src="http://url.to/src.jpg" style="width:146;height:109;float:left">

This works with height and width but I can't get the style-element "float:left" added 这适用于高度和宽度,但我无法添加样式元素“ 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);

result of this will be 结果将是

<img  alt="" style="width:146;height:109" src="http://url.to/src.jpg" style="float:left">

which didn't work because of the double style element 由于双重风格元素而无法使用

Try the following regular expression 试试下面的正则表达式

<?php

$html='<img alt="" width="146" height="109" src="http://placehold.it/140x200" style="float:left" />';
$pattern = '/(<img.*)width="(\d+)" height="(\d+)"(.*style=")(.*)" \/(>)/';
$style = '$1$4width:$2px;height:$3px;$5';
$html = preg_replace($pattern, $style, $html);
echo $html; //view source of page to see the code change

?>

Note the use of brackets '(' ')' to create groups matched that can be later referenced using $1 $2 etc go to regex101.com and try out the regular expression. 请注意,使用方括号'('')'创建匹配的组,以后可以使用$ 1 $ 2等进行引用 ,请访问regex101.com并尝试使用正则表达式。

Above code will result in following, except the last part, that shouldn't matter but you can modify it further. 上面的代码将导致以下内容(除了最后一部分)无关紧要,但是您可以进一步对其进行修改。

<img alt="" src="http://placehold.it/140x200" style="width:146;height:109;float:left" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM