[Yii Framework] A component of cutting string

1. Create a file named "StringHelper.php", and locate it in protected/components , and insert the code as below:

代码
<?php
/**
*/
class StringHelper extends CApplicationComponent
{
public function substr($string, $start = 0, $length = 0, $append = '...')
{
$stringLast = "";
if ($start < 0 || $length < 0 || strlen($string) <= $length)
{
$stringLast = $string;
}
else
{
$i = 0;
while ($i < $length)
{
$stringTMP = substr($string, $i, 1);
if ( ord($stringTMP) >=224 )
{
$stringTMP = substr($string, $i, 3);
$i = $i + 3;
}
elseif( ord($stringTMP) >=192 )
{
$stringTMP = substr($string, $i, 2);
$i = $i + 2;
}
else
{
$i = $i + 1;
}
$stringLast[] = $stringTMP;
}
$stringLast = implode("",$stringLast);
if(!empty($append))
{
$stringLast .= $append;
}
}
return $stringLast;
}
}

 




 

 

2. Demo

Yii::import("application.components.StringHelper");
$stringHelper = new StringHelper;
echo $stringHelper->substr('This is a test string!', 0, 8);

 




 


Have fun with Yii! :)

posted @ 2010-08-23 23:26  DavidHHuan  阅读(357)  评论(0编辑  收藏  举报