简体   繁体   中英

PHP - how to determine the width of an character string

I've got a customer who would like to determine the length of a string entered via a web form. The case of the string may be mixed.

The assumption is that the font size is 1" in height, ie. approx. 72 point.

A 72 point, lower case 's' printed is narrower than a upper case 'S'.

I need to display the result in inches.

Is there a way within PHP to calculate the width of a string??

You would need to grab the text, and convert it into an image, using the font at the correct size, etc. this isn't too much of a task to get working with php thankfully. For this case I'm going to assume some details on the font, etc but please use your own data.

   <?php
    $text = "my string of text";

    $img = $imagecreatetruecolor(100,100); // SIZE DOESN'T MATTER REALLY THIS TIME
    $fontSize = 72; //FONT SIZE
    $fontFile = "arial.ttf" // PUT THE RELEVANT FONT FILE IN THE SAME DIRECTORY AS THIS SCRIPT
    $boundingBox = imagettfbbox($fontSize, 0, $fontFile, $text); //RETRIEVE THE BOUNDING BOX OF THE TEXT RENDERED
    $width = $boundingBox[2] - $boundingBox[0]; //WIDTH IN PIXELS AT 72dpi
    $inchesWidth = $width/72;
    echo $inchesWidth;
    ?>

It's not going to be 100% accurate due to differences in spacing across systems but should give you a good guestimate.

This is referenced in the Unicode Standard Annex #11 East Asian Width , so we have to parse the following file:

# Unicode Character Database
# For documentation, see http://www.unicode.org/reports/tr44/
#
# East_Asian_Width Property
#
# This file is a normative contributory data file in the
# Unicode Character Database.
#
# The format is two fields separated by a semicolon.
# Field 0: Unicode code point value or range of code point values
# Field 1: East_Asian_Width property, consisting of one of the following values:
#         "A", "F", "H", "N", "Na", "W"

00AB;N           # Pi         LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
00AC;Na          # Sm         NOT SIGN
00AD;A           # Cf         SOFT HYPHEN
00AE;A           # So         REGISTERED SIGN
00AF;Na          # Sk         MACRON
00B0;A           # So         DEGREE SIGN
00B1;A           # Sm         PLUS-MINUS SIGN
00B2..00B3;A     # No     [2] SUPERSCRIPT TWO..SUPERSCRIPT THREE
00B4;A           # Sk         ACUTE ACCENT
00B5;N           # Ll         MICRO SIGN
00B6..00B7;A     # Po     [2] PILCROW SIGN..MIDDLE DOT
(...)

http://www.unicode.org/Public/UCD/latest/ucd/EastAsianWidth.txt

http://www.unicode.org/reports/tr11/tr11-38.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM