php按照指定長度截取字符串的代碼

phpw34 9年前發布 | 754 次閱讀 PHP

php按照指定長度截取字符串的代碼,如果字符串超出了指定的長度,會用...替換,不過這段代碼不支持中英文的區分

<?php
//if a string is longer than the defined length, 
//it will add 3 periods to the end of the string.
//you can change it to what ever you want for example:
//return substr($str,0,$len).'[<a href="read_more.html">Read More</a>]';
//http://www.sharejs.com
function strLength($str,$len){
    $lenght = strlen($str);
    if($lenght > $len){
        return substr($str,0,$len).'...';
    }else{
        return $str;
    }
}
$str = "This is a fairly long string.";
//The fist part is the string, the second part is how long it can be
echo strLength($str,10).'<br>';
echo strLength($str,30);
?> 

 本文由用戶 phpw34 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!