A
A
alexkl2010-10-14 12:58:26
PHP
alexkl, 2010-10-14 12:58:26

The substr and strlen function in php does not work correctly with Russian characters. How to solve the problem?

The substr and strlen function in php does not work correctly with Russian characters (utf8 encoding). Tried mb_substr also - didn't help.
Who will help solve the problem?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
L
LIAL, 2010-10-14
@LIAL

and in what incorrectness that is expressed, it is possible to learn???

A
alexkl, 2010-10-14
@alexkl

Here is an example function:
/**
* shortenText
* @param string
* @param int
* @param bool, default true
* @since 1.0.9
*/
function shortenText( $text, $count, $addbb=true )
{
if( $count > 0 )
{
$totalchars = strlen( $text );
$charcount = 0;
$fulltext = $text;
$buffer = '';
if( $totalchars >= $count )
{
$bbcode = false;
while( strlen( $fulltext ) > 0 )
{
$char = $fulltext{0};
if( $char == '[' ) $bbcode = true;
if( ( $bbcode && $addbb ) || $charcount < $count ) $buffer .= $char;
$fulltext = substr( $fulltext, 1 );
if( !$bbcode ) $charcount++;
if( $char == ']' ) $bbcode = false;
}
$text = $buffer.( $charcount >= $count? '...': '' );
}
}
return $text;
}
If $fultext is in English letters, everything is ok. Reduces. If Russian - empty string

I
iStyx, 2010-10-14
@iStyx

1. Use mb_substr, mb_strlen with $encoding='utf-8'
2. Don't use $char=$fulltext{0}, replace with mb_substr

W
witbier, 2010-10-14
@witbier

iconv_substr($s, $from, $len, 'UTF-8')
iconv_strlen($s, 'UTF-8')
$s{$i} ==> iconv_substr($s, $i, 1, 'UTF- eight')

Z
Zyava, 2010-10-14
@Zyava

Your $bbcode is always $false, is that normal? The code is hilarious...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question