0

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 !

Hymed Ghenai
  • 199
  • 15

2 Answers2

1

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);
Prince Dorcis
  • 955
  • 7
  • 7
0

The default national language setting (NLS) used in mbstring. Note that this option automagically defines mbstring.internal_encoding and mbstring.internal_encoding should be placed after mbstring.language in php.ini

https://www.php.net/manual/en/mbstring.configuration.php

Legioneroff
  • 139
  • 5