简体   繁体   中英

Make every first character uppercase in array

I'm trying to get all my first characters in a PHP array to be uppercase.

PHP code:

<?php
$ordlista = file_get_contents('C:/wamp/www/bilder/filmlista.txt');

$ord = explode("\n", $ordlista);

sort($ord,SORT_STRING);

foreach ($ord as $key => $val) {
    echo $val."<br/>";
}
?>
$ord = array_map('ucfirst', $ord);
$ord=array_map(function($word) { return ucfirst($word); }, $ord);

To support UTF-8 multibyte characters, like "Russian" for example, you would need

$ord = array_map(function($str){
    return mb_strtoupper(mb_substr($str, 0, 1)).mb_strtolower(mb_substr($str, 1));
}, $ord);

This uses the mb_ucfirst function from https://stackoverflow.com/a/14161325/175071

Sometimes, the raw data would looks something like this:

$ord = ['apple', 'GUAVA', 'mango', 'BANANA'];

To full-proof this:

$ord = array_map('ucfirst', array_map('strtolower', $ord));

What this does is it converts everything into a lower case first, then capitalize each word.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM