Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : String Functions : ucfirst

ucfirst

Make a string's first character uppercase (PHP 4, PHP 5)
string ucfirst ( string str )

Example 2482. ucfirst() example

<?php
$foo
= 'hello world!';
$foo = ucfirst($foo);             // Hello world!

$bar = 'HELLO WORLD!';
$bar = ucfirst($bar);             // HELLO WORLD!
$bar = ucfirst(strtolower($bar)); // Hello world!
?>

Related Examples ( Source code ) » ucfirst



Code Examples / Notes » ucfirst

michael

This is what you would expect php to deliver if there was a built-in function named ucsentence.
function ucsentence ($string){
$string = explode ('.', $string);
$count = count ($string);
for ($i = 0; $i < $count; $i++){
$string[$i]  = ucfirst (trim ($string[$i]));
if ($i > 0){
$string[$i] = '&nbsp;&nbsp;' . $string[$i];
}
}
$string = implode ('.', $string);
return $string;
}


info

This is a simple code to get all the 'bad words', stored in a database, out of the text. You could use str_ireplace but since that's installed on PHP5 only, this works as well. It strtolowers the text first then places capitals with ucfirst() where it thinks a capital should be placed, at a new sentence. The previous sentence is ended by '. ' then.
<?php
function filter($text){
$filters=mysql_query("SELECT word,result FROM filter");
while($filter=mysql_fetch_array($filters)){
$text=str_replace($filter[word],$filter[result],strtolower($text));
$parts=explode(". ",$text);
for($i=0;$i<count($parts);$i++){
$parts[$i]=ucfirst($parts[$i]);
}
$text=implode(". ",$parts);
}
return $text;
}
?>


lazaro_tolentino

this is a advance ucfirst function, for upper especifics words, with config in array of seperator
/**
* @return string
* @param string $str frase que passará pelo parce
* @desc Pega uma frase e devolve a mesma com as palavras com suas
* maiusculas  obedecendo um criterio configurado no array $string_sep
*
* @since 2004-04-01 15:04 adicionado a variavel $tring_sep que é um
* array contendo todos os separadores a serem usados
*/
function str_upper_lower($str)
{
/**
* array contendo todos os separadores
*/
$string_sep=array(' ','-','/','_','.');
/**
* coloca todas as palavras com letras minusculas
*/
$str=strtolower($str);

/**
* testa todos os separadores
*/
for ($i=0;$i<count($string_sep);$i++)
{
$sep=$string_sep[$i];
/**
* separa a frase usando os separador atual
*/
$array_words = explode($sep, $str);

/**
* variavel que conterá o valor temporario
*/
$tmp_str = '';
$i2=0;
foreach ($array_words as $word)
{
/**
* se a quantidade de caracteres for maior que dois, ou se conter ponto,
*  devolve upper da primeira letra
*/
$tmp_str .=(strlen($word)>2 || strpos($word,'.')?ucfirst($word):$word);
/**
* não adiciona o separador no fim de strings
*/
if ($i2<count($array_words)-1)
{
$tmp_str .= $sep;
}
$i2++;
}
$str = $tmp_str;
}
return $str;
}


stig-arne grönroos

This function does not work as expected with characters from non-English alphabets (I only tested it with scandinavian letters, åäö => ÅÄÖ). It leaves them as lowercase.
Someone already commented that the function doesn't work on html entities, which is somewhat understandable. This bug however takes place before I convert the strings to html.


26-oct-2006 03:45

Some simple function for cyrillic and latin letters both:
function rucfirst($str) {
   if(ord(substr($str,0,1))<192) return ucfirst($str);
else
return chr(ord(substr($str,0,1))-32).substr($str,1);
}


plemieux

Simple multi-bytes ucfirst():
<?php
function my_mb_ucfirst($str) {
$fc = mb_strtoupper(mb_substr($str, 0, 1));
return $fc.mb_substr($str, 1);
}
?>


northie

Sentence Case:
<?php
function SentenceCase($str) {
$sentences = explode(". ",$str);
for($i=0;$i<count($sentences);$i++) {
$sentences[$i][0] = strtoupper($sentences[$i][0]);
}
return implode(". ",$sentences);
}
?>


markus ernst

plemieux' function did not work for me without passing the encoding to every single mb function (despite ini_set('default_charset', 'utf-8') at the top of the script). This is the example that works in my application (PHP 4.3):
<?php
function my_mb_ucfirst($str, $e='utf-8') {
   $fc = mb_strtoupper(mb_substr($str, 0, 1, $e), $e);
   return $fc.mb_substr($str, 1, mb_strlen($str, $e), $e);
}
?>


04-mar-2004 05:46

Of course ucfirst() will _not_ convert html entities such as &uuml; (u-Umlaut as ü) to &Uuml; which would represent Ü.

steven

Note: the return for this function changed in versions 4.3 when a string is passed of length 0.  In <4.2 false is returned and in >4.3 a string of length 0 is returned.
Example:
$name = ucfirst("");
var_dump($name);
$name = ucfirst("owen");
var_dump($name);
Results for <4.2:
bool(false) string(4) "Owen"
Results for >4.3:
string(0) "" string(4) "Owen"


27-jul-2006 10:31

lcfirst - In case you need to get the original string back after a ucfirst.
   function lcfirst( $str ) {
       $str[0] = strtolower($str[0]);
       return $str;
   }


adefoor

Ken and zee
One thing I would do to make this more unviersally work would be to add strtolower() around your $sentence.  Doing this will allow you to convert an all caps text block as well as an all lowercase text block.
<?php
function sentence_cap($impexp, $sentence_split) {
   $textbad=explode($impexp, $sentence_split);
   $newtext = array();
   foreach ($textbad as $sentence) {
       $sentencegood=ucfirst(strtolower($sentence));
       $newtext[] = $sentencegood;
   }
   $textgood = implode($impexp, $newtext);
   return $textgood;
}
$text = "this is a sentence. this is another sentence! this is the fourth sentence? no, this is the fourth sentence.";
$text = sentence_cap(". ",$text);
$text = sentence_cap("! ",$text);
$text = sentence_cap("? ",$text);
echo $text; // This is a sentence. This is another sentence! This is the fourth sentence? No, this is the fourth sentence.
?>


ami hughes ami

In the event you sort of need multiple delimiters to apply the same action to, you can preg_replace this "second delimiter" enveloping it with your actual delimiter.

A for instance, would be if you wanted to use something like Lee's FormatName function in an input box designed for their full name as this script was only designed to check the last name as if it were the entire string.  The problem is that you still want support for double-barreled names and you still want to be able to support the possibility that if the second part of the double-barreled name starts with "mc", that it will still be formatted correctly.
This example does a preg_replace that surrounds the separator with your actual delimiter.  This is just a really quick alternative to writing some bigger fancier blah-blah function.  If there's a shorter, simpler way to do it, feel free to inform me.  (Emphasis on shorter and simpler because that was the whole point of this.) :D
Here's the example.  I've removed Lee's comments as not to confuse them with my own.
<?php
  function FormatName($name=NULL)
  {
      if (empty($name))
          return false;
  $name = strtolower($name);
  $name = preg_replace("[\-]", " - ",$name); // Surround hyphens with our delimiter so our strncmp is accurate
  if (preg_match("/^[a-z]{2,}$/i",$name))  // Simple preg_match if statement
  {
     
      $names_array = explode(' ',$name);  // Set the delimiter as a space.

      for ($i = 0; $i < count($names_array); $i++)
      {
          if (strncmp($names_array[$i],'mc',2) == 0 || ereg('^[oO]\'[a-zA-Z]',$names_array[$i]))
          {
          $names_array[$i][2] = strtoupper($names_array[$i][2]);
          }
          $names_array[$i] = ucfirst($names_array[$i]);
         
      }

      $name = implode(' ',$names_array);
  $name = preg_replace("[ \- ]", "-",$name); //  Remove the extra instances of our delimiter
      return ucwords($name);
     
  }
  }
?>


carel

I made a small change. Now it takes care of points in numbers
function ucsentence ($string){
  $string = explode ('.', $string);
  $count = count ($string);
  for ($i = 0; $i < $count; $i++){
      $string[$i]  = ucfirst (trim ($string[$i]));
      if ($i > 0){
          if ((ord($string[$i]{0})<48) || (ord($string[$i]{0})>57)) {
     $string[$i] = ' ' . $string[$i];
  }  
      }
  }
  $string = implode ('.', $string);
  return $string;
}


lee benson

Here's a function I threw together when needing to validate name entries (both first name and last name).
This allows simple formatting for names prefixed with "Mc" (like McDonald, McCulloch, etc) and names prefixed with O (like O'Reilly, O'Conner, etc)..
It also allows double-barrelled names to be formatted correctly, in the Smith-Jones way.
Here's the function...
<?php
function FormatName($name=NULL) {

/* Formats a first or last name, and returns the formatted
version */

if (empty($name))
return false;

// Initially set the string to lower, to work on it
$name = strtolower($name);

// Run through and uppercase any multi-barrelled names
$names_array = explode('-',$name);
for ($i = 0; $i < count($names_array); $i++) {

// "McDonald", "O'Conner"..
if (strncmp($names_array[$i],'mc',2) == 0 || ereg('^[oO]\'[a-zA-Z]',$names_array[$i])) {
$names_array[$i][2] = strtoupper($names_array[$i][2]);

}

// Always set the first letter to uppercase, no matter what
$names_array[$i] = ucfirst($names_array[$i]);

}
// Piece the names back together
$name = implode('-',$names_array);
// Return upper-casing on all missed (but required) elements of the $name var
return ucwords($name);

}
?>
If you have any other "rules" to follow for international/foreign naming rules, you can add them to the foreach loop, and it should still follow all of the other rules.
It's a quick fix, but it seems to do the job nicely.
Examples...
<?php
$name = "o'cONNER-MCdOnAld";
echo FormatName($name);
?>
Returns: O'Conner-McDonald


bartuc

Here is the fixed function for Turkish alphabet..
<?php
function uc_first($str){
  $str[0] = strtr($str,
  "abcdefghýijklmnopqrstuvwxyz".
  "\x9C\x9A\xE0\xE1\xE2\xE3".
  "\xE4\xE5\xE6\xE7\xE8\xE9".
  "\xEA\xEB\xEC\xED\xEE\xEF".
  "\xF0\xF1\xF2\xF3\xF4\xF5".
  "\xF6\xF8\xF9\xFA\xFB\xFC".
  "\xFE\xFF",
  "ABCDEFGHIÝJKLMNOPQRSTUVWXYZ".
  "\x8C\x8A\xC0\xC1\xC2\xC3\xC4".
  "\xC5\xC6\xC7\xC8\xC9\xCA\xCB".
  "\xCC\xCD\xCE\xCF\xD0\xD1\xD2".
  "\xD3\xD4\xD5\xD6\xD8\xD9\xDA".
  "\xDB\xDC\xDE\x9F");
  return $str;
}
?>


bkimble

Here is a handy function that makes the first letter of everything in a sentence upercase. I used it to deal with titles of events posted on my website ... I've added exceptions for uppercase words and lowercase words so roman numeral "IV" doesn't get printed as "iv" and words like "a" and "the" and "of" stay lowercase.
function RemoveShouting($string)
{
$lower_exceptions = array(
       "to" => "1", "a" => "1", "the" => "1", "of" => "1"
);
                                     
$higher_exceptions = array(
       "I" => "1", "II" => "1", "III" => "1", "IV" => "1",
       "V" => "1", "VI" => "1", "VII" => "1", "VIII" => "1",
       "XI" => "1", "X" => "1"
);
$words = split(" ", $string);
$newwords = array();

foreach ($words as $word)
{
       if (!$higher_exceptions[$word])
               $word = strtolower($word);
       if (!$lower_exceptions[$word])
               $word = ucfirst($word);
        array_push($newwords, $word);

}
       
return join(" ", $newwords);  
}


zee

Another way to capitalize first letter of every sentence in a text, I hope it will help someone. It won't convert non-English characters, though, and ignores sentences ending with ! or ? etc.
<?php
$text="this is a sentence. this is another sentence.";
$split=explode(". ", $text);
foreach ($split as $sentence) {
$sentencegood=ucfirst($sentence);
$text=str_replace($sentence, $sentencegood, $text);
}
echo $text; // This is a sentence. This is another sentence.
?>


13-mar-2005 01:11

Ah, the last code were spoiled, here is the fixed one:
<?php
function uc_first($str){
$str[0] = strtr($str,
"abcdefghijklmnopqrstuvwxyz".
"\x9C\x9A\xE0\xE1\xE2\xE3".
"\xE4\xE5\xE6\xE7\xE8\xE9".
"\xEA\xEB\xEC\xED\xEE\xEF".
"\xF0\xF1\xF2\xF3\xF4\xF5".
"\xF6\xF8\xF9\xFA\xFB\xFC".
"\xFD\xFE\xFF",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".
"\x8C\x8A\xC0\xC1\xC2\xC3\xC4".
"\xC5\xC6\xC7\xC8\xC9\xCA\xCB".
"\xCC\xCD\xCE\xCF\xD0\xD1\xD2".
"\xD3\xD4\xD5\xD6\xD8\xD9\xDA".
"\xDB\xDC\xDD\xDE\x9F");
return $str;
}
?>
So, this function changes also other letters into uppercase, ucfirst() does only change: a-z to: A-Z.


markus ernst

A combination of the below functions to enable ucfirst for multibyte strings in a shared hosting environment (where you can not always count on mbstring to be installed):
<?php
function my_mb_ucfirst($str, $e='utf-8') {
   if (function_exists('mb_strtoupper')) {
       $fc = mb_strtoupper(mb_substr($str, 0, 1, $e), $e);
       return $fc.mb_substr($str, 1, mb_strlen($str, $e), $e);
   }
   else {
       $str = utf8_decode($str);
       $str[0] = strtr($str[0],
           "abcdefghýijklmnopqrstuvwxyz".
           "\x9C\x9A\xE0\xE1\xE2\xE3".
           "\xE4\xE5\xE6\xE7\xE8\xE9".
           "\xEA\xEB\xEC\xED\xEE\xEF".
           "\xF0\xF1\xF2\xF3\xF4\xF5".
           "\xF6\xF8\xF9\xFA\xFB\xFC".
           "\xFE\xFF",
           "ABCDEFGHÝIJKLMNOPQRSTUVWXYZ".
           "\x8C\x8A\xC0\xC1\xC2\xC3\xC4".
           "\xC5\xC6\xC7\xC8\xC9\xCA\xCB".
           "\xCC\xCD\xCE\xCF\xD0\xD1\xD2".
           "\xD3\xD4\xD5\xD6\xD8\xD9\xDA".
           "\xDB\xDC\xDE\x9F");
       return utf8_encode($str);
   }
}
?>


uwe

@adefoor, Ken and Zee
Changing the case can only be done by understanding the text. Take for example "USA", "Sunday", "March", "I am ...", abbreviations like "prob." and so on.


ken kehler

@ zee: this should solve your !, ?, and any punctuations you want to add. It can probably be cleaned up a bit.
<?php
function sentence_cap($impexp, $sentence_split) {
$textbad=explode($impexp, $sentence_split);
$newtext = array();
foreach ($textbad as $sentence) {
$sentencegood=ucfirst($sentence);
$newtext[] = $sentencegood;
}
$textgood = implode($impexp, $newtext);
return $textgood;
}
$text = "this is a sentence. this is another sentence! this is the fourth sentence? no, this is the fourth sentence.";
$text = sentence_cap(". ",$text);
$text = sentence_cap("! ",$text);
$text = sentence_cap("? ",$text);
echo $text; // This is a sentence. This is another sentence! This is the fourth sentence? No, this is the fourth sentence.
?>


Change Language


Follow Navioo On Twitter
addcslashes
addslashes
bin2hex
chop
chr
chunk_split
convert_cyr_string
convert_uudecode
convert_uuencode
count_chars
crc32
crypt
echo
explode
fprintf
get_html_translation_table
hebrev
hebrevc
html_entity_decode
htmlentities
htmlspecialchars_decode
htmlspecialchars
implode
join
levenshtein
localeconv
ltrim
md5_file
md5
metaphone
money_format
nl_langinfo
nl2br
number_format
ord
parse_str
print
printf
quoted_printable_decode
quotemeta
rtrim
setlocale
sha1_file
sha1
similar_text
soundex
sprintf
sscanf
str_getcsv
str_ireplace
str_pad
str_repeat
str_replace
str_rot13
str_shuffle
str_split
str_word_count
strcasecmp
strchr
strcmp
strcoll
strcspn
strip_tags
stripcslashes
stripos
stripslashes
stristr
strlen
strnatcasecmp
strnatcmp
strncasecmp
strncmp
strpbrk
strpos
strrchr
strrev
strripos
strrpos
strspn
strstr
strtok
strtolower
strtoupper
strtr
substr_compare
substr_count
substr_replace
substr
trim
ucfirst
ucwords
vfprintf
vprintf
vsprintf
wordwrap
eXTReMe Tracker