今天要实现这么一个功能: php实现英文自动换行,并在最后一行加"-"
CSS:? word-break:break-all;可以实现自动换行,但是没有办法实现加"-",
开始考虑用截取指定字符的方法实现一行显示固定长度的字符,但测试的时候发现,每个字母占有的像素宽度是不一样的。
所以写了下面的代码,但是效果还是不好。 最后没办法,只有手动加“-"了。以后再研究一下。
<?php function enauto_break($words, $len) { if($len <2) return $words; $words_len = strlen($words); $html_out = ""; $add_times = 7;$end = 0; for($i=0;$i<$add_times;$i++) { if($end>=$words_len) break; //echo 'now len '. $end; $t_temp = pa_substr($words, $end, $len, $end); // echo ' se len '. $end; $tail_word = substr($words, $end, 1); if(preg_match('/[a-zA-Z]/', $tail_word)) { $html_out .= $t_temp . '-<br/>'; }else{ $html_out .= $t_temp . '`<br/>'; } } $html_out .= substr($words, $end); return $html_out; } //针对排版的取字符函数,大写字母占二个字符位置 //$len 这里表示像素值,不是字符数目,注意! function pa_substr($words, $start, $len, &$end) { $arial_array = array('a' => 10, 'b' => 9, 'c' => 9, 'd' => 9, 'e' => 10, 'f' => 7, 'g' => 9, 'h' => 9, 'i' => 2, 'j' => 4, 'k' => 9, 'l' => 2, 'm' => 14, 'n' => 9, 'o' => 10, 'p' => 9, 'q' => 9, 'r' => 6, 's' => 9, 't' => 5, 'u' => 9, 'v' => 11, 'w' => 15, 'x' => 10, 'y' => 9, 'z' => 9, ',' => 4, 'A' => 13, 'B' => 11, 'C' => 13, 'D' => 12, 'E' => 11, 'F' => 10, 'G' => 14, 'H' => 12, 'I' => 2, 'J' => 8, 'K' => 12, 'L' => 9, 'M' => 15, 'N' => 12, 'O' => 14, 'P' => 11, 'Q' => 14, 'R' => 12, 'S' => 12, 'T' => 12, 'U' => 12, 'V' => 13, 'W' => 21, 'X' => 14, 'Y' => 14, 'Z' => 12, '(' => 2, ')' => 2, ); $now_pos = $start; $html_out = ''; $now_get_len = 0; while($now_get_len<$len) { $t_temp = substr($words, $now_pos++, 1); if(empty($arial_array[$t_temp])) { $now_get_len += 7; }else { $now_get_len +=$arial_array[$t_temp]; } $html_out .= $t_temp; } $end = $now_pos; return $html_out; } ?>$arial_array是自己根据图片自己设置的。效果不好的原来,应该有这个有关系吧。没有好的方法得到字母所占像素的宽度。