2010-01-23 16 views

Odpowiedz

30

Bo tną swoje postacie na pół.

Użyj mb_substr dla kodowania znaków wielobajtowych, np. UTF-8. substr po prostu liczy bajty, podczas gdy mb_substr zlicza znaki.

0

Wystarczy przedłużyć Gurmbo jest odpowiedź. Używanie mb_substr rozwiąże Twój problem, ale nadal, jeśli znaki specjalne pojawią się na końcu, gdy potkniesz się, nadal pokazuje niektóre znaki specjalne. Więc kiedy zrobiłem kilka badań, wordpress o metodzie wp_html_excerpt, aby rozwiązać ten problem.

Metoda wp_html_excerpt usuwa te znaki specjalne z końca wiersza.

Oto source code z wordpress.

/** 
* Safely extracts not more than the first $count characters from html string. 
* 
* UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT* 
* be counted as one character. For example & will be counted as 4, < as 
* 3, etc. 
* 
* @since 2.5.0 
* 
* @param string $str String to get the excerpt from. 
* @param int $count Maximum number of characters to take. 
* @param string $more Optional. What to append if $str needs to be trimmed. Defaults to empty string. 
* @return string The excerpt. 
*/ 
function wp_html_excerpt($str, $count, $more = null) { 
    if (null === $more) 
     $more = ''; 
    $str = wp_strip_all_tags($str, true); 
    $excerpt = mb_substr($str, 0, $count); 
    // remove part of an entity at the end 
    $excerpt = preg_replace('/&[^;\s]{0,6}$/', '', $excerpt); 
    if ($str != $excerpt) 
     $excerpt = trim($excerpt) . $more; 
    return $excerpt; 
} 
0

Jeśli masz problemy kodowania można również zastosować funkcję html_entity_decode(), które przekształcają wszystkie podmioty HTML do ich obowiązujących znaków. Na przykład:

echo substr(html_entity_decode($string_to_cut), 0, 28) . "..."; 

To również powinno zadziałać.

Powiązane problemy