PHP:包装的测试行长度
作者:互联网
如何测试块是否超出图像大小并将该文本包装到下一行.不确定我是否使用if语句正确执行此操作.
$text="Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem http://somelongurl.com/then-we-make-it-super-long-with-some-more/ Lorem Ipsum Lorem Ipsum Lorem Ipsum";
$string_chunks = explode(' ', $text);
foreach ($string_chunks as $chunk) {
if($end_x + $chunk > $image_width){
$start_x = 5;
$start_y += 20;
}
$coords = imagettfbbox($fontsize, $angle, $font, $chunk);
$end_x = $coords[0] + $coords[4] + 10;
$color_to_draw = is_a_url($chunk) ? $linkcolor : $black;
imagettftext($im, $fontsize, $angle, $start_x, $start_y, $color_to_draw, $font, $chunk);
$start_x += $end_x;
}
使用此代码,我得到:
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem
http://somelongurl.com/then-we-make-it-super-long-with-some-more/
Lorem Ipsum Lorem Ipsum Lorem Ipsum
我想要发生的是:
Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem http://somelongurl.com/then-we
-make-it-super-long-with-some-more/
Lorem Ipsum Lorem Ipsum Lorem Ipsum
解决方法:
我想我知道你想要达到的目的.我没有测试下面的代码,所以它可能需要一些抛光和重新/测试.但它应该给你一个很好的起点
<?php
$text = "Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem http://somelongurl.com/then-we-make-it-super-long-with-some-more/ Lorem Ipsum Lorem Ipsum Lorem Ipsum";
$string_chunks = explode(' ', $text);
foreach ($string_chunks as $chunk) {
$_start_bit = false;
// before anything else check if chunk is url
$color_to_draw = is_a_url($chunk) ? $linkcolor : $black;
// check if chunk is to long
if(strlen($chunk) > $image_width) {
// if there is allredy a word in the current line
// make the first bit $imagewidth - current line width
if ($start_x > 5) {
$_start_bit = substr($chunk, 0, ($image_width - $start_x));
$chunk = str_replace($_start_bit, "", $chunk);
}
$_chunkbits = wordwrap($chunk, $image_width, "\n", true);
$_chunkbits = explode("\n", $_chunkbits);
if($_start_bit) {
array_unshift($_chunkbits, $_start_bit);
}
// loop bits and draw them
foreach ($_chunkbits as $bit) {
if($end_x + $bit > $image_width){
$start_x = 5;
$start_y += 20;
}
$coords = imagettfbbox($fontsize, $angle, $font, $bit);
$end_x = $coords[0] + $coords[4] + 10;
imagettftext($im, $fontsize, $angle, $start_x, $start_y, $color_to_draw, $font, $bit);
$start_x += $end_x;
}
unset($_chunkbits);
} else {
if($end_x + $chunk > $image_width){
$start_x = 5;
$start_y += 20;
}
$coords = imagettfbbox($fontsize, $angle, $font, $chunk);
$end_x = $coords[0] + $coords[4] + 10;
imagettftext($im, $fontsize, $angle, $start_x, $start_y, $color_to_draw, $font, $chunk);
$start_x += $end_x;
}
}
标签:php,width,textwrapping 来源: https://codeday.me/bug/20190630/1341778.html