2012-08-13 33 views
0

我有以下函數來截斷文本:截斷字符串逃過forien charasters

/** 
    * Removes HTML tags, crops to 255 symbols 
    * 
    * @param string $unformatted 
    */ 
    public function formatShortDescr($unformatted) { 
     if(strlen($unformatted)<1) return; 

     $long_text = strip_tags(trim($unformatted)); 
     $max_length = 255; 

     if(strlen($long_text) > $max_length){ 
      $short_text = (substr($long_text,0,$max_length)); 
     } else { 
      $short_text = $long_text; 
     } 
     return $short_text; 
    } 

如這樣的: <p>Victory har utvecklats f&ouml;r att passa den &auml;gare som beh&ouml;ver en kompakt, ........被轉換成:Victory har utvecklats f&ouml;r att passa den &a

我怎樣才能將其設置爲從不降價的字符串一半通過打破html實體的方式?

回答

1

應該很容易先轉換實體到正常的字符,然後使用mb_strlen(因爲...的2字節字符,UTF8)檢查長度和mb_substring截斷,然後再轉換回實體...

$long_text = strip_tags(trim($unformatted)); 
    $long_text = html_entity_decode($long_text); 

    $long_text = mb_strlen($long_text) > $max_length ? mb_substr($long_text, 0, $max_length) : $long_text; 

    return htmlentities($long_text); 
1

它有時適用的另一種方法是在最後一個空格處截斷。它取決於你是否想要255個字符,或者你想要可讀的東西,但有用的副作用是你不必擔心HTML實體。

例如:

$string = "this is the long test string to test with"; 
$limit = 20; 

$result = substr($string, 0, strrpos($string, " ", -$limit)-1); 
echo $result; // "this is the long"