-2

How do i go from this

width="200" height="300"

to this with php

width:200px; height:300px;

Basically i want to remove the quotes and equal signs and insert a semi colon after each attribute

Pinkie
  • 10,126
  • 22
  • 78
  • 124
  • Presumably moving from html attributes to an in-line style attribute? – David Thomas Jan 08 '12 at 20:06
  • @cillosis getimagesize(x) gives an html width and height attr. I want to convert that to inline css – Pinkie Jan 08 '12 at 20:11
  • If it's not some special case, don't replace it for images. It would make sense the other way around (from inline style to `width` and `height` attributes). See: http://stackoverflow.com/questions/1247685/should-i-specify-height-and-width-attributes-for-my-imgs-in-html – pawel Jan 08 '12 at 20:45

3 Answers3

2

You can use 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;
?>
Paker
  • 2,522
  • 1
  • 16
  • 27
1

You can use str_replace or a regular expression.

As concrete example:

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

But beware, if there are also other attributes or s.th. else - regular expressions could be the better way.

fkerber
  • 1,032
  • 9
  • 24
  • html attribute does not contain px. It looks like `width="200" height="300"` – Pinkie Jan 08 '12 at 20:09
  • You are right but I copied the string from initial query, it must have been changed afterwards, I will adjust my answer. – fkerber Jan 08 '12 at 20:11
  • @DavidThomas yes, it replaces each occurence of "= with : – fkerber Jan 08 '12 at 20:12
  • Oh, I see - you are right - my mistake. It should read =" - I will update it. – fkerber Jan 08 '12 at 20:30
  • @fkerber thanks this works, although i think paker has a more bullet proof solution. Different browsers may add additional spaces between attributes or use ' instead of ". – Pinkie Jan 08 '12 at 20:55
0

Just don't use that output format of getimagesize() if you're not going to include it directly.

Use first two values:

list($width, $height) = getimagesize("img/flag.jpg");
echo 'width:'.$width.'px; height:'.$height.'px;';
user
  • 23,260
  • 9
  • 113
  • 101