Capitalize First word in PHP

9.4k Views Asked by At

As i am using PHP, So problem comes to me that how can i captilized the first Letter In this Code.

<?php foreach($aa as $row):?>

<?php echo ''.$row->username.'' ?>
<?php endforeach; ?>
4

There are 4 best solutions below

0
MatthewMcGovern On

Php has a ucfirst() function it Make a string's first character uppercase.

<?php echo ''.ucfirst($row->username).'' ?>

0
Savv On

it'd be easier for you to use CSS instead of a PHP function to display this.

use this line of CSS:

text-transform: capitalize;
0
Filippo oretti On

Safe UTF-8 method

<?php echo asd($row->firstname); ?>

    function asd($string){
     if(mb_strlen($string)){
     return mb_strtoupper(mb_substr($string,0,1)).mb_substr($string,1,mb_strlen($string));
    }else{
     return false;
    }
    }

but in Codeigniter you can just do:

$this->load->helper('string');
echo humanize($row->username);

Third case (the one i prefer usually) is to use CSS class:

.capitalize{
 text-transform:capitalize;
}

<a class="capitalize"><?php echo $row->firstname; ?></a>
0
user410932 On

ucfirst() will help you, but note that it will only convert the first to upper case. All others can also be in upper case, so you may want those to be converted to lower case first.

<?php echo ucfirst(strtolower($row->username)); ?>