PHP を使用してテキストを特定の幅のボックスにラップする方法を探しています。動的なテキスト文字列が入ってきて、フォント サイズが可変です。
私はこのスレッドからテキストを好きなように切り取る素晴らしい方法を見つけました: PHP で長い単語をよりスマートにワードラップしますか?
このコード ブロックを使用すると、次のようになります。
function smart_wordwrap($string, $width = 10, $break = "\n") {
// 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);
}
これはうまく機能しますが、設定されたピクセル寸法 (制約ボックス) とフォント サイズを上記に入力する方法を見つける必要があります。上記の関数は文字数を使用しています。フォントサイズが非常に小さい場合は、明らかに文字数を大きくする必要があり、その逆も同様です。
次の変数がある場合、とにかくこれを行うことができますか?
$boxWidth = 200(px);
$text = (dynamic string);
$font = 'customfont.ttf'
$fontSize = (dynamic size);
ワードラップ機能への別のループを考えていました。または、その機能がどのように機能するか完全にはわからないため、「爆発」を編集する方法があるかもしれません。