Home  >  Article  >  Backend Development  >  PHP string interception length custom method

PHP string interception length custom method

高洛峰
高洛峰Original
2016-10-21 10:27:20984browse

Let’s introduce below how to use PHP custom function to intercept the length of characters we want to intercept, and use ellipsis to replace or hide the excess part.


String interception method:

//截取字符串长度
function cut($Str, $Length,$more=true) {
    //$Str为截取字符串,$Length为需要截取的长度
    global $s;
    $i = 0;
    $l = 0;
    $ll = strlen($Str);
    $s = $Str;
    $f = true;
    while ($i <= $ll) {
        if (ord($Str{$i}) < 0x80) {
            $l++; $i++;
        } else if (ord($Str{$i}) < 0xe0) {
            $l++; $i += 2;
        } else if (ord($Str{$i}) < 0xf0) {
            $l += 2; $i += 3;
        } else if (ord($Str{$i}) < 0xf8) {
            $l += 1; $i += 4;
        } else if (ord($Str{$i}) < 0xfc) {
            $l += 1; $i += 5;
        } else if (ord($Str{$i}) < 0xfe) {
            $l += 1; $i += 6;
        }
         
        if (($l >= $Length - 1) && $f) {
            $s = substr($Str, 0, $i);
            $f = false;
        }
         
        if (($l > $Length) && ($i < $ll) && $more) {
            $s = $s . &#39;...&#39;; 
            break; 
            //如果进行了截取,字符串末尾加省略符号“...”
        }
    }
    return $s;
}

Usage method:

$str = &#39;看看截取到哪里?&#39;;
echo cut($str,1);
echo &#39;<br>&#39;;
echo cut($str,4);
echo &#39;<br>&#39;;
echo cut($str,5);
echo &#39;<br>&#39;;
echo cut($str,5,false);
echo &#39;<br>&#39;;
 
$str = &#39;中英文混合看看hello?&#39;;
echo cut($str,18);
echo &#39;<br>&#39;;
echo cut($str,50);

Output:

看...
看看...
看看...
看看
中英文混合看看hel...
中英文混合看看hello?

Explanation: Generally, UTF-8 format is 3 bytes, while GBK compatible gb2312 is generally 2 bytes, above Take UTF-8 encoding as an example.

The ellipsis mode can be switched on and off through the third parameter $more. The default value is true for with ellipses, and false for no ellipses.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn