用于分割字符串的两个 PHP 函数 - ○白子○ 的Blog

用于分割字符串的两个 PHP 函数

[ 2009-09-09 22:16:25 | Author: seaboat ]
Font Size: Large | Medium | Small
新作了两个函数,结果没用上,放在在这儿以备用。
/**
 * 按词分割字符串
 * @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;
}
[Last Modified By seaboat, at 2009-09-29 21:19:47]
Comments Feed Comments Feed: http://www6.webng.com/seaboat/feed.asp?q=comment&id=760

There is no comment on this article.

Post Comment
Smilies
[smile] [confused] [cool] [cry]
[eek] [angry] [wink] [sweat]
[lol] [stun] [razz] [redface]
[rolleyes] [sad] [yes] [no]
[heart] [star] [music] [idea]
Enable UBB Codes
Auto Convert URL
Show Smilies
Hidden Comment
Username:   Password: