用于分割字符串的两个 PHP 函数
Thursday, 10. September 2009, 02:05:20
/**
* 按词分割字符串
* @param $str 元字符串
* @param $maxLength 单词最大长度
* @return array
*/
function splitInWords($str, $maxLength = 16) {
if(empty($str)) return array();
if($maxLength <= 0) $maxLength = 1;
$rawWords = explode(' ', $str);
$words = array();
foreach($rawWords as $word) {
$len = mb_strlen($word);
if($len > $maxLength) {
$pos = 0;
while($len > $maxLength) {
$words[] = mb_substr($word, $pos, $maxLength);
$pos += $maxLength;
$len -= $maxLength;
}
$words[] = mb_substr($word, $pos, $maxLength);
} else {
$words[] = $word;
}
}
return $words;
}
/**
* 按行(指定长度)分割字符串
* @param $str 元字符串
* @param $length 每行最大字符数
* @return array
*/
function splitInLines($str, $length = 80) {
$lines = array();
foreach(split("\n", $str) as $s) {
preg_match_all("/./u", $s, $matches);
$arr = $matches[0];
for($i = 0; $i < ceil(count($arr)/$length); $i++) {
$lines[] = join("", array_slice($arr, $i*$length, $length));
}
}
return $lines;
}








