<?php
function substring($str, $start, $len){
$strlen = strlen($str);
if($start > $strlen){
return "";
}
for($i = 0; $i < $start; $i++){
if(ord($str[$i]) > 0x7f ){
$start++;
$i++;
}
}
for($i=0; $i < $len; $i++) {
if(ord($str[$i+$start]) > 0x7f){
$len++;
$i++;
}
}
return substr($str, $start, $len);
}
// 切词函数,有时用在mysql 全文检索上
function wordSegment($str, $len)
{
$startPos = 0;
$strLen = $real_strLen = strlen($str);
for($i = 0; $i < $real_strLen; $i++){
if(ord($str[$i]) > 0x7f ){
php程序员站
$strLen--;
$i++;
}
}
$rltStrArray = array();
while(($strLen - $startPos) >= $len )
{
$rltStrArray[] = substring($str, $startPos++, $len);
}
return $rltStrArray;
}
$testStr = "nbs v1.0beta测试版发布!";
echo $testStr . "\r\n";
print_r(wordSegment($testStr, 3));
?>
运行结果:Array ( [0] => nbs v1 [1] => bs v1. [2] => s v1.0 [3] => v1.0b [4] => v1.0be [5] => 1.0bet [6] => .0beta [7] => 0beta测 [8] => beta测试 [9] => eta测试版 [10] => ta测试版发 [11] => a测试版发布 [12] => 测试版发布!