Skip to content

Instantly share code, notes, and snippets.

@Homlean
Created December 7, 2012 03:45
Show Gist options
  • Save Homlean/4230608 to your computer and use it in GitHub Desktop.
Save Homlean/4230608 to your computer and use it in GitHub Desktop.
php string 截取
// 字符截取
// Truncate ?
function strCut($sourceStr, $cutLength) {
$result = '';
$i = 0;
$n = 0;
$sourceStrLen = strlen($sourceStr);
while (($n < $cutLength) and ($i <= $sourceStrLen)) {
$temp = substr($sourceStr, $i, 1);
$asciiCode = ord($temp);
if ($asciiCode >= 224) {
$result = $result . substr($sourceStr, $i, 3);
$i = $i + 3;
$n++;
} elseif ($asciiCode >= 192) {
$result = $result . substr($sourceStr, $i, 2);
$i=$i+2;
$n++;
} elseif ($asciiCode >= 65 && $asciiCode <= 90) {
$result = $result . substr($sourceStr, $i, 1);
$i = $i + 1;
$n++;
} else {
$result = $result . substr($sourceStr, $i, 1);
$i = $i + 1;
$n = $n + 0.5;
}
}
if ($sourceStrLen > $cutLength) {
$result = $result . '...';
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment