How to determine the length (in pixels) of a string being rendered on a web page? How to determine the length (in pixels) of a string being rendered on a web page? php php

How to determine the length (in pixels) of a string being rendered on a web page?


Use the PHP function imagettfbbox to get the size of the bounding box for the given string.

On the other hand you can use also javascript to manipulate SVG images in case you would like to handle it on the client side. That way it wouldn't even matter if the client had the specified font or not...


You could use PHP GD to render out the string as a image and get the size of the resulting image.

If you use this, it should work:

   list($left,, $right) = imageftbbox( 12, 0, "arial.ttf", "Hello World");   $width = $right - $left;


Your title and actual post seem to say slightly different things. I'm guessing what you're really asking is whether it's possible to determine the width in pixels of text rendered on a web page in your PHP code (prior to web page being rendered).

If so, the answer is "NO". Said font may not be available on user's computer; s/he may have custom stylesheet applied; use large font sizes; etc...

What you can do is determine that width using javascript after the page is rendered (obviously, you can do that in some other page as well and hope nothing changes till then) and submit that back to PHP. With some clever AJAX-ing you can even do this on the same page.

Take a look at this question for details on how to do this in javascript.