2010-01-23 17 views
8

Estoy usando la función substr() para limitar los caracteres en cadenas. pero a veces, el texto de salida contiene algunos caracteres oscuros y signos de interrogación, etc. ...¿Por qué mi php substr() muestra caracteres oscuros al cortar un texto?

el texto "substimado" ya está codificado en UTF8, y NO en entidades html para hacer que este problema sea similar.

Gracias

+0

¿Podría dar un ejemplo de la cadena antes y después? – robertbasic

Respuesta

30

Porque estás cortando a tus personajes a la mitad.

Use mb_substr para codificación de caracteres multibyte como UTF-8. substr solo cuenta los bytes mientras que mb_substr cuenta los caracteres.

0

Sólo para extender el Gurmbo es la respuesta. Usar mb_substr resolverá tu problema, pero si aparecen caracteres especiales al final cuando te tropieces, todavía muestra algunos caracteres especiales. Entonces, cuando investigué, Wordpress tenía el método wp_html_excerpt para resolver este problema.

El método wp_html_excerpt elimina esos caracteres especiales del final de la línea.

Aquí está el source code de 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

Si usted tiene problemas de codificación también se puede aplicar la función html_entity_decode() que convierten todas las entidades HTML a sus caracteres correspondientes. Por ejemplo:

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

Eso también debería funcionar.

Cuestiones relacionadas