2012-01-08 30 views
-1

如何从这个PHP HTML转换宽度height属性内联风格

width="200" height="300" 

去这个用PHP

width:200px; height:300px; 

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

+0

大概从HTML移动属性的内嵌样式属性? – 2012-01-08 20:06:47

+0

@cillosis getimagesize(x)给出了html的宽度和高度attr。我想将其转换为嵌入式css – Pinkie 2012-01-08 20:11:25

+0

如果不是特殊情况,请不要将其替换为图像。这是有道理的(从内联样式到'width'和'height'属性)。请参阅:http://stackoverflow.com/questions/1247685/should-i-specify-height-and-width-attributes-for-my-imgs-in-html – pawel 2012-01-08 20:45:26

回答

2

您可以使用正则表达式:

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

您可以使用str_replace或regu年轻的表达。

至于具体的例子:

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

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

+0

html属性不包含px。它看起来像'width =“200”height =“300”' – Pinkie 2012-01-08 20:09:57

+0

你是对的,但我从最初的查询中复制了字符串,它必须在之后改变,我会调整我的答案。 – fkerber 2012-01-08 20:11:08

+0

@DavidThomas是的,它取代了每一次出现的“= with: – fkerber 2012-01-08 20:12:55

0

只是,如果你不打算直接包括它不使用的getimagesize()是输出格式。

使用前两个值:

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