1. 简单的,只能分2行;
1 //$str:输入字符串; 2 //$num:超过多少个字符后进行换行(换行后每行的最大字符数) 3 function forceBlackString($str, $num){ 4 if(strlen($str)>$num){ 5 $tempStr = substr($str,0,$num); 6 $lastStr = substr($str,$num); 7 $str = $tempStr.‘<br>‘.$lastStr; 8 } 9 return $str; 10 }
2.加强版,强制换行
1 function forceBlackStringEx($str, $num){ 2 //1.先算出字符串总长度 3 $str_length = strlen($str); 4 //2.计算最多能够分成几个子字符串 5 $strNum = $str_length/$num>0 ? ($str_length/$num) : ($str_length/$num)+1; 6 $resultStr = ‘‘; 7 //3.循环截取 8 for($i=0; $i<$strNum; $i++){ 9 $resultStr .= ‘<br>‘.substr($str, $i*$num,$num); 10 } 11 //4.去掉结果字符串开头多余的 <br>,长度位4 12 $resultStr = substr($resultStr, 4); 13 return $resultStr; 14 }
时间: 2024-11-08 16:12:43