I'm looking for a way to wrap text into a box of specific width using PHP. I have dynamic text strings coming in, and variable font sizes.
I found a great way to cut the text up the way I want it from this thread:
Smarter word-wrap in PHP for long words?
Using this block of code:
function smart_wordwrap($string, $width = 10, $break = "
") {
// split on problem words over the line length
$pattern = sprintf('/([^ ]{%d,})/', $width);
$output = '';
$words = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
foreach ($words as $word) {
if (false !== strpos($word, ' ')) {
// normal behaviour, rebuild the string
$output .= $word;
} else {
// work out how many characters would be on the current line
$wrapped = explode($break, wordwrap($output, $width, $break));
$count = $width - (strlen(end($wrapped)) % $width);
// fill the current line and add a break
$output .= substr($word, 0, $count) . $break;
// wrap any remaining characters from the problem word
$output .= wordwrap(substr($word, $count), $width, $break, true);
}
}
// wrap the final output
return wordwrap($output, $width, $break);
}
This works great, but I need to find a way to feed a set pixel dimension (the constraining box), and font size into the above. The above function is using a character count - and if the font-size is very small obviously the character count needs to be larger and vice versa.
Is there anyway I could do this if I have the following variables?
$boxWidth = 200(px);
$text = (dynamic string);
$font = 'customfont.ttf'
$fontSize = (dynamic size);
I was thinking another loop to the word wrap function. Or maybe there's a way to edit the "explode" as I'm not entirely sure how that function works.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…