1

I want to get an array with only the first character from an existing array. This is my code:

$tag_array = array('ächzen', 'ßüß', 'test');


function firstCharArray($array){
    $result = array();
    foreach($array as $item){
        $result[] = $item[0];
    }

    return $result;
}

$characters = firstCharArray($tag_array);
echo '<pre>';
print_r($characters);
echo '</pre>';

The problem is that I get � for umlauts. The script is encoded in UTF-8 without BOM. I don't know what I'm doing wrong. I also tried to set the locale but it doesn't helped so far.

4

1 回答 1

5

Change the

$result[] = $item[0];

to

$result[] = mb_substr($item, 0, 1, "utf-8");

You are getting the first byte of a multi-byte character.

于 2013-08-01T14:49:54.690 回答