Yii Framework Forum: [share] A component of cutting string - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

[share] A component of cutting string Rate Topic: -----

#1 User is offline   Davidhhuan 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 270
  • Joined: 08-September 09

Posted 23 August 2010 - 10:24 AM

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! :)
no pain, no gain...

My Blog : http://cnblogs.com/davidhhuan
My website: http://sharefamily.net/
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users