string - PHP: Get width in pixel of text including "normal" text and emoji's -
i want trim given text @ given number of pixels.
to achieve this, loop through length of text , each loop, add next character , measure string of method imagettfbbox
. - works fine me on "normal text's" e.g. posting. ;)
but if add emoji's text, length shorter expected. think because emojis encoded more 1 byte. - that's why, i'm using mb_strwidth
, mb_substr
.
the method imagettfbbox
expects font-file measure given string. font able display emoji's.
here's code
$line = "🏡 garden, 🕓 clock, other things"; $maxlength = 100; // pixel // start looping through line, start 15 characters ( $len = 15; $len < mb_strwidth($line); $len++ ) { // grep x chars line $newline = mb_substr($line, 0, $len); // measure string $fontbox = imagettfbbox(12, 0, "fonts/opensansemoji.ttf", $newline); $textwidth = $fontbox[2]; // compare measured string given max length if ( $textwidth > $maxlength ) { $line = mb_substr($line, 0, $len - 2) . "..."; break; } } $line = newline;
expample lines
"🏡 garden, 🕓 clock, other things" "🏡🏡🏡🏡🏡🏡🏡🏡🏡🏡🏡🏡🏡🏡🏡🏡 gaaaaaaaaaaaardeeeeeeeeeeeeeeeeeen" "mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm" "iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii" "erufgbwuiergbvfuipwervbpiuwebvruiwbevuibwüeriuvbwieuörvböwieuvbr"
as can see, more emoji's use, shorter line.
kind regards non native speaker. :)
Comments
Post a Comment