Scott’s Technical Blog

Measuring Pixel Size of String in PHP

by scott on Sep.10, 2009, under php

I frequently find myself needing to approximate the pixel width of strings on the server side in PHP. The function below does that nicely. It WILL NOT return the exact number of pixels for all font in all cases, but the approximation can be used to switch CSS classes. I’ll do a measurement and then wrap a code block with a class of “strink” if I think the string will be too long for the display.

You can do a better job in Javascript, but this is good enough for most cases.

/**
* This function uses the array below to calculate the pixel width of a string
* of characters. The widths of each character are based on a 12px Helvetica font.
* Kerning is not taken into account so RESULTS ARE APPROXIMATE.
*
* The purpose is to return a relative size to help in formatting. For example,
*
* strPixels('I like cake') == 54
* strPixels('I LIKE CAKE') == 67
*
* @param string $string characters to measure size
*
* @return integer size in pixels.
*/
public static $strPixelWidths = array(
' ' => 3, '!' => 3, '"' => 4, '#' => 7, '$' => 7, '%' => 11, '&' => 8, ''' => 2, '(' => 4, ')' => 4, '*' => 5, '+' => 7, ',' => 3, '-' => 4,
'.' => 3, '/' => 3, '0' => 7, '1' => 7, '2' => 7, '3' => 7, '4' => 7, '5' => 7, '6' => 7, '7' => 7, '8' => 7, '9' => 7, ':' => 3, ';' => 3,
'<' => 7, '=' => 7, '>' => 7, '?' => 7, '@' => 12, 'A' => 7, 'B' => 8, 'C' => 9, 'D' => 9, 'E' => 8, 'F' => 7, 'G' => 9, 'H' => 9, 'I' => 3,
'J' => 6, 'K' => 8, 'L' => 7, 'M' => 9, 'N' => 9, 'O' => 9, 'P' => 8, 'Q' => 9, 'R' => 9, 'S' => 8, 'T' => 7, 'U' => 9, 'V' => 7, 'W' => 11,
'X' => 7, 'Y' => 7, 'Z' => 7, '[' => 3, '\' => 3, ']' => 3, '^' => 5, '_' => 7, '`' => 4, 'a' => 7, 'b' => 7, 'c' => 6, 'd' => 7, 'e' => 7,
'f' => 3, 'g' => 7, 'h' => 7, 'i' => 3, 'j' => 3, 'k' => 6, 'l' => 3, 'm' => 11, 'n' => 7, 'o' => 7, 'p' => 7, 'q' => 7, 'r' => 4, 's' => 7,
't' => 3, 'u' => 7, 'v' => 5, 'w' => 9, 'x' => 5, 'y' => 5, 'z' => 5, '{' => 4, '|' => 3, '}' => 4, '~' => 7);

public static function strPixels($string) {
  $weight = 0;
  if (!empty($string)) {
    for ($i = 0; $i < strlen($string); $i++) {
      $w = @self::$strPixelWidths[substr($string, $i, 1)];
      if ($w) $weight += $w;
    }
  }

  return $weight;
}
:

Leave a Reply

Security Code:

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...

Archives

All entries, chronologically...