PHP将html宽度-高度属性转换为内联样式


PHP convert html width height attribute to inline style

如何从此开始

width="200" height="300"

使用php实现此功能

width:200px; height:300px;

基本上,我想删除引号和等号,并在每个属性后插入一个分号

您可以使用regexp:

<?php
  $html = 'width="200" height="300"';
  $pattern = '/width="('d+)"'s+height="('d+)"/';
  preg_match($pattern, $html, $matches);
  $style = "width:".$matches[1]."px; height:".$matches[2]."px;";
  echo $style;
?>

您可以使用str_replace或正则表达式。

具体示例:

 $string = 'width="200" height="300"'
 $string = str_replace('="', ':', $string);
 $string = str_replace('"', 'px;', $string);

但请注意,如果还有其他属性或s.th.else,正则表达式可能是更好的方法。

如果不直接包含getimagesize(),就不要使用它的输出格式。

使用前两个值:

list($width, $height) = getimagesize("img/flag.jpg");
echo 'width:'.$width.'px; height:'.$height.'px;';