商品名と価格、氏名と年齢などのように左右に分かれる表を PHP を使って出力する例です。
スペースを使って文字を埋めているので等幅フォントを使えば数値部分だけ右寄せしたように見せることができます。
指定した文字数を超えた場合は自動的に改行されるのでテキストメールのように1行の長さが決まっている場合に便利だと思います。
引数は (文字列1, 文字列2, 左の文字数, 右の文字数, 区切り文字) となっています。
たまねぎ 400円 牛肉 1,200円 魚沼産コシヒ 2,780円 カリ 4kg プチトマト 300円
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | <?php function textTable( $text1 , $text2 , $length1 , $length2 , $spacing = ' ' ){ $result = '' ; $text1 = breakString( $text1 , $length1 ); $text2 = breakString( $text2 , $length2 ); $lines1 = preg_split( '/\R/' , $text1 ); $lines2 = preg_split( '/\R/' , $text2 ); $lineCount1 = count ( $lines1 ); $lineCount2 = count ( $lines2 ); $maxLines = max( $lineCount1 , $lineCount2 ); for ( $i = 0; $i < $maxLines ; $i ++){ $line1 = isset( $lines1 [ $i ]) ? $lines1 [ $i ] : '' ; $line2 = isset( $lines2 [ $i ]) ? $lines2 [ $i ] : '' ; $pad1 = str_repeat ( ' ' , $length1 - mb_strwidth( $line1 )); $pad2 = str_repeat ( ' ' , $length2 - mb_strwidth( $line2 )); $result .= $line1 . $pad1 . $spacing ; $result .= $pad2 . $line2 ; $result .= PHP_EOL; } return $result ; } function breakString( $text , $length , $eol =PHP_EOL, $encoding =null){ if ( ! $encoding ) $encoding = mb_internal_encoding(); $textLen = mb_strlen( $text , $encoding ); $chars = []; $width = 0; $result = '' ; for ( $i = 0; $i < $textLen ; $i ++){ $char = mb_substr( $text , $i , 1, $encoding ); if ( $width + mb_strwidth( $char , $encoding ) > $length ){ $result .= $eol . $char ; $width = mb_strwidth( $char , $encoding ); } else { $result .= $char ; $width += mb_strwidth( $char , $encoding ); } } return $result ; } $items = [ [ 'たまねぎ' , '400円' ], [ '牛肉' , '1,200円' ], [ '魚沼産コシヒカリ 4kg' , '2,780円' ], [ 'プチトマト' , '300円' ] ]; ?> <!DOCTYPE html> <html lang= "ja" > <head> <meta charset= "UTF-8" > <meta name= "viewport" content= "width=device-width, initial-scale=1.0" > <meta http-equiv= "X-UA-Compatible" content= "ie=edge" > <title>Document</title> </head> <body> <pre style= "font-family: 'Osaka-mono', 'Osaka-等幅', 'MS ゴシック', monospace;" ><?php foreach ( $items as $item ){ $result = textTable( $item [0], $item [1], 12, 8); echo htmlspecialchars( $result , ENT_QUOTES, 'UTF-8' ); } ?></pre> </body> </html> |