Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cutting a string with accents [duplicate]

Possible Duplicate:
Truncate a multibyte String to n chars

Hello,

I'm developing a site in French and I created a function that cuts string after X number of characters. It works great, but when the last character has an accent, it has the (?) instead of the character.

Here is my function

function neat_trim3($str, $n, $delim='...') {
    $len = strlen($str);
    if ($len > $n) {
        $tocut = $len-$n;
        $output = substr($str,0,-$tocut);
        return $len.' - '.$output.$delim;
    }
    else {
        return $str;
    }
}

Example

$str = "C'est une soirée privé ce soir";
echo eat_trim3($str, 15 , '...' );   
// GIVES ME             C'est une soir�...

The rest of the page echos the page perfectly, I can even echo the same string without the cut and it works great.

Any help appreciated.

Thanks.

like image 989
denislexic Avatar asked May 15 '11 11:05

denislexic


People also ask

How can I replace an accented character with a normal character in PHP?

Since a lot of people have upvoted this answer, it needs to be said that the safer way is to use chr() instead of hard-coded accented characters, due to different editors the file may be opened with.

How do you change an accented character to a regular character?

replace(/[^a-z0-9]/gi,'') . However a more intuitive solution (at least for the user) would be to replace accented characters with their "plain" equivalent, e.g. turn á , á into a , and ç into c , etc.


1 Answers

Use the mb_substr and mb_strlen functions. It doesn't work because you are using UTF-8, which has multi-byte characters and you cut the in the middle.

like image 143
Lukáš Lalinský Avatar answered Sep 26 '22 11:09

Lukáš Lalinský