【问题标题】:PHP convert html width height attribute to inline stylePHP将html宽度高度属性转换为内联样式
【发布时间】:2014-02-25 01:56:26
【问题描述】:

我该怎么做

width="200" height="300"

用 php 做到这一点

width:200px; height:300px;

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

【问题讨论】:

  • 大概是从 html 属性转移到内联样式属性?
  • @cilosis getimagesize(x) 给出了 html 的宽度和高度属性。我想将其转换为内联 css
  • 如果不是特殊情况,请不要将其替换为图像。反过来也有意义(从内联样式到widthheight 属性)。见:stackoverflow.com/questions/1247685/…

标签: php


【解决方案1】:

你可以使用正则表达式:

<?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;
?>

【讨论】:

    【解决方案2】:

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

    具体例子:

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

    但要注意,如果还有其他属性或某事。 else - 正则表达式可能是更好的方法。

    【讨论】:

    • html 属性不包含 px。看起来像width="200" height="300"
    • 你是对的,但是我从初始查询中复制了字符串,之后肯定已经更改了,我会调整我的答案。
    • @DavidThomas 是的,它将每次出现的 "= 替换为:
    • 哦,我明白了 - 你是对的 - 我的错误。它应该是 =" - 我会更新它。
    • @fkerber 感谢这项工作,尽管我认为 paker 有一个更防弹的解决方案。不同的浏览器可能会在属性之间添加额外的空格或使用 ' 而不是 ".
    【解决方案3】:

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

    使用前两个值:

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

    【讨论】:

      猜你喜欢
      • 2016-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-28
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      • 2015-10-16
      相关资源
      最近更新 更多