Skip to content
Advertisement

PHP function to adapt texte not working with special characters?

i’m struggling with a function that adapts a text depending of the first letter of a string.

            $str = "élo";

            function deD($str) { 
            return (in_array(mb_strtolower($str[0]), array('a', 'e', 'é', 'è', 'ê', 'h', 'i', 'o', 'u')) ? 'd'' : 'de ').$str;
            }
            
            echo deD($str).'</br>';
            echo $str[0];

OUTPUT: de élo �

EXPECTED OUTPUT: d’élo é

Basically, mb_strtolower should prevent all special characters to be miss-read. I tried different options, but i still get it wrong. I’d like the function to work with all accent types.

Any idea ?

Thanks a lot from France !

Advertisement

Answer

You need to set utf-8 encoding for the file. Try to put this at the top:

header('Content-type: text/html; charset=utf-8');

Then, instead of $str[0], use mb_substr($str, 0, 1)

function deD($str) {
    return (in_array(mb_strtolower(mb_substr($str, 0, 1)), array('a', 'e', 'é', 'è', 'ê', 'h', 'i', 'o', 'u')) ? 'd'' : 'de ').$str;
}

$str = 'élo';

echo deD($str).'<br>';
echo mb_substr($str, 0, 1);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement