Error de substr() de la función PHP


Cuando uso substr() obtengo un carácter extraño al final

$articleText = substr($articleText,0,500);

Tengo una salida de 500 caracteres y

¿Cómo puedo arreglar esto? Es un problema de codificación? Mi idioma es el griego.

 24
Author: alimack, 2009-12-29

7 answers

substr está contando usando bytes, y no caracteres.

Griego probablemente significa que está utilizando alguna codificación multi-byte, como UTF-8 and y contar por bytes no es muy bueno para ellos.

Tal vez usando mb_substr podría ayudar, aquí: el mb_* las funciones han sido creadas específicamente para codificaciones multibyte.

 56
Author: Pascal MARTIN,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-29 09:08:48

Uso mb_substr en su lugar, es capaz de tratar con múltiples codificaciones, no solo cadenas de un solo byte como substr:

$articleText = mb_substr($articleText,0,500,'UTF-8');
 19
Author: Uğur Özpınar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-29 14:11:16

Parece que estás cortando un carácter unicode por la mitad. Uso mb_substr en su lugar, para cortar cadenas de forma segura con unicode.

 6
Author: deceze,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-29 09:10:06

Solución alternativa para cadenas codificadas UTF-8: esto convertirá UTF - 8 a caracteres antes de cortar la sub-cadena.

$articleText = substr(utf8_decode($articleText),0,500);

Para obtener la cadena articleText de vuelta a UTF-8, se necesitará una operación adicional:

$articleText = utf8_encode( substr(utf8_decode($articleText),0,500) );
 1
Author: Kristoffer Bohmann,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-30 17:15:43

Use esta función, funcionó para mí

function substr_unicode($str, $s, $l = null) {
    return join("", array_slice(
        preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l));
}

Créditos: http://php.net/manual/en/function.mb-substr.php#107698

 1
Author: Moussawi7,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-14 02:53:53

Ms_substr() también funciona de manera excelente para eliminar los extraños saltos de línea finales, con los que estaba teniendo problemas después de analizar el código html. El problema no fue manejado por:

 trim() 

O:

 var_dump(preg_match('/^\n|\n$/', $variable));

O:

str_replace (array('\r\n', '\n', '\r'), ' ', $text)

No cojas.

 0
Author: Solar Nick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-18 00:59:30

Usted está tratando de cortar unicode character.So preferí en lugar de substr() intentar mb_substr() en php.

Substr()

substr ( string $string , int $start [, int $length ] )

Mb_substr()

mb_substr ( string $str , int $start [, int $length [, string $encoding ]] )

Para más información sobre substr () - Credits = > Marque aquí

 0
Author: GowriShankar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-27 12:52:24