我有一位客户希望确定通过网络表单输入的字符串的长度。字符串的情况可能是混合的。
假设字体大小为1"高度,即。约。 72分。
72分,小写'印刷品比大写字母窄......'
我需要以英寸显示结果。
PHP中有没有办法计算字符串的宽度?
答案 0 :(得分:0)
您需要抓取文本,并使用正确大小的字体将其转换为图像,等等。感谢使用php并不是太多的任务。对于这种情况,我将假设有关字体等的一些细节,但请使用您自己的数据。
<?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;
?>
由于系统之间的间距不同,它不会100%准确,但应该给你一个很好的猜测。
答案 1 :(得分:0)
这在 Unicode 标准附件 #11 中被引用 东亚宽度,所以我们要解析如下文件:
# 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