用于分割字符串的两个 PHP 函数
[ 2009-09-09 22:16:25 | Author: seaboat ]
新作了两个函数,结果没用上,放在在这儿以备用。
Comments Feed: http://www6.webng.com/seaboat/feed.asp?q=comment&id=760
/**
* 按词分割字符串
* @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;
}
* 按词分割字符串
* @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: http://www6.webng.com/seaboat/feed.asp?q=comment&id=760
There is no comment on this article.






