Word case in php

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

mb_convert_casePerform case folding on a string

Description

mb_convert_case(string $string, int $mode, ?string $encoding = null): string

Parameters

string

The string being converted.

mode

The mode of the conversion. It can be one of
MB_CASE_UPPER,
MB_CASE_LOWER,
MB_CASE_TITLE,
MB_CASE_FOLD,
MB_CASE_UPPER_SIMPLE,
MB_CASE_LOWER_SIMPLE,
MB_CASE_TITLE_SIMPLE,
MB_CASE_FOLD_SIMPLE.

encoding

The encoding
parameter is the character encoding. If it is omitted or null, the internal character
encoding value will be used.

Return Values

A case folded version of string converted in the
way specified by mode.

Changelog

Version Description
7.3.0 Added support for
MB_CASE_FOLD,
MB_CASE_UPPER_SIMPLE,
MB_CASE_LOWER_SIMPLE,
MB_CASE_TITLE_SIMPLE, and
MB_CASE_FOLD_SIMPLE
as mode.

Examples

Example #1 mb_convert_case() example


<?php
$str
= "mary had a Little lamb and she loved it so";
$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
echo
$str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
echo
$str; // Prints Mary Had A Little Lamb And She Loved It So
?>

Example #2 mb_convert_case() example with non-Latin UTF-8 text


<?php
$str
= "Τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός";
$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
echo
$str; // Prints ΤΆΧΙΣΤΗ ΑΛΏΠΗΞ ΒΑΦΉΣ ΨΗΜΈΝΗ ΓΗ, ΔΡΑΣΚΕΛΊΖΕΙ ΥΠΈΡ ΝΩΘΡΟΎ ΚΥΝΌΣ
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
echo
$str; // Prints Τάχιστη Αλώπηξ Βαφήσ Ψημένη Γη, Δρασκελίζει Υπέρ Νωθρού Κυνόσ
?>

Notes

By contrast to the standard case folding functions such as
strtolower() and strtoupper(),
case folding is performed on the basis of the Unicode character
properties. Thus the behaviour of this function is not affected
by locale settings and it can convert any characters that have
‘alphabetic’ property, such a-umlaut (ä).

For more information about the Unicode properties, please see » http://www.unicode.org/reports/tr21/.

See Also

  • mb_strtolower() — Make a string lowercase
  • mb_strtoupper() — Make a string uppercase
  • strtolower() — Make a string lowercase
  • strtoupper() — Make a string uppercase
  • ucfirst() — Make a string’s first character uppercase
  • ucwords() — Uppercase the first character of each word in a string

alNzy

3 years ago


You can use this function to fix problems related to Turkish "ı", "I", "i", "İ" characters. This function also replaces the weird "i̇" character with regular "i" character ("i̇ => i").

function mb_convert_case_tr($str, $type, $encoding = "UTF-8")
{

  switch ($type) {
    case "u":
    case "upper":
    case MB_CASE_UPPER:
      $type = MB_CASE_UPPER;
      break;
    case "l":
    case "lower":
    case MB_CASE_LOWER:
      $type = MB_CASE_LOWER;
      break;
    case "t":
    case "title":
    case MB_CASE_TITLE:
      $type = MB_CASE_TITLE;
      break;
  }

  $str = str_replace("i", "İ", $str);
  $str = str_replace("I", "ı", $str);

  $str = mb_convert_case($str, $type, $encoding);
  $str = str_replace("i̇", "i", $str);

  return $str;
}


agash at freemail dot hu

13 years ago


as the previouly posted version of this function doesn't handle UTF-8 characters, I simply tried to replace ucfirst to mb_convert_case, but then any previous case foldings were lost while looping through delimiters.
So I decided to do an mb_convert_case on the input string (it also deals with words is uppercase wich may also be problematic when doing case-sensitive search), and do the rest of checking after that.

As with mb_convert_case, words are capitalized, I also added lowercase convertion for the exceptions, but, for the above mentioned reason, I left ucfirst unchanged.

Now it works fine for utf-8 strings as well, except for string delimiters followed by an UTF-8 character ("Mcádám" is unchanged, while "mcdunno's" is converted to "McDunno's" and "ökrös-TÓTH éDUa" in also put in the correct form)

I use it for checking user input on names and addresses, so exceptions list contains some hungarian words too.

<?phpfunction titleCase($string, $delimiters = array(" ", "-", ".", "'", "O'", "Mc"), $exceptions = array("út", "u", "s", "és", "utca", "tér", "krt", "körút", "sétány", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX", "XX", "XXI", "XXII", "XXIII", "XXIV", "XXV", "XXVI", "XXVII", "XXVIII", "XXIX", "XXX" )) {
      
/*
        * Exceptions in lower case are words you don't want converted
        * Exceptions all in upper case are any words you don't want converted to title case
        *   but should be converted to upper case, e.g.:
        *   king henry viii or king henry Viii should be King Henry VIII
        */
       
$string = mb_convert_case($string, MB_CASE_TITLE, "UTF-8");

       foreach (

$delimiters as $dlnr => $delimiter){
              
$words = explode($delimiter, $string);
              
$newwords = array();
               foreach (
$words as $wordnr => $word){

                                      if (

in_array(mb_strtoupper($word, "UTF-8"), $exceptions)){
                              
// check exceptions list for any words that should be in upper case
                              
$word = mb_strtoupper($word, "UTF-8");
                       }
                       elseif (
in_array(mb_strtolower($word, "UTF-8"), $exceptions)){
                              
// check exceptions list for any words that should be in upper case
                              
$word = mb_strtolower($word, "UTF-8");
                       }

                                              elseif (!

in_array($word, $exceptions) ){
                              
// convert to uppercase (non-utf8 only)$word = ucfirst($word);

                                                      }

array_push($newwords, $word);
               }
              
$string = join($delimiter, $newwords);
       }
//foreach
      
return $string;
}
?>


dave at wp dot pl

6 years ago


MB_CASE_TITLE doesn't change letters in quotation marks.

Example:
mb_convert_case('AAA "aaa"', MB_CASE_TITLE);
// Result: Aaa "aaa"


Rasa Ravi at tantrajoga dot cz

17 years ago


For CZECH characters:
<?php
$text
= mb_convert_case($text, MB_CASE_LOWER, "Windows-1251");
?>
The right encoding Windows-1250 is not valid (see the list mb_list_encodings), but Windows-1251 will do the same 100%. The function strtolower() ignores czech characters with diacritics.

info at yasarnet dot com

14 years ago


For my case following did the work to capitalize UTF-8 encoded string.

function capitalize($str, $encoding = 'UTF-8') {
    return mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding) . mb_strtolower(mb_substr($str, 1, mb_strlen($str), $encoding), $encoding);
}


tavhane at gmail dot com

5 years ago


for turkish simple:

$str = mb_convert_case(str_replace(['i','I'], ['İ','ı'], $str), MB_CASE_TITLE,"UTF-8");


the at psychoticneurotic dot com

14 years ago


Building upon Justin's and Alex's work...

This function allows you to specify which delimiter(s) to explode on (not just the default space). Now you can correctly capitalize Irish names and hyphenated words (if you want)!

<?php

function titleCase($string, $delimiters = array(" ", "-", "O'"), $exceptions = array("to", "a", "the", "of", "by", "and", "with", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X")) {

      
/*

        * Exceptions in lower case are words you don't want converted

        * Exceptions all in upper case are any words you don't want converted to title case

        *   but should be converted to upper case, e.g.:

        *   king henry viii or king henry Viii should be King Henry VIII

        */

      
foreach ($delimiters as $delimiter){

              
$words = explode($delimiter, $string);

              
$newwords = array();

               foreach (
$words as $word){

                       if (
in_array(strtoupper($word), $exceptions)){

                              
// check exceptions list for any words that should be in upper case

                              
$word = strtoupper($word);

                       } elseif (!
in_array($word, $exceptions)){

                              
// convert to uppercase

                              
$word = ucfirst($word);

                       }

                      
array_push($newwords, $word);

               }

              
$string = join($delimiter, $newwords);

       }

       return
$string;

}

?>


Anonymous

1 year ago


$str = "Τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός";
$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
this convertation does not give the example that you already post
but this one

$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
"ΤΆΧΙΣΤΗ ΑΛΏΠΗΞ ΒΑΦΉΣ ΨΗΜΈΝΗ ΓΗ, ΔΡΑΣΚΕΛΊΖΕΙ ΥΠΈΡ ΝΩΘΡΟΎ ΚΥΝΌΣ"


webenformasyon at gmail dot com

5 years ago


for turkish language I => i  and i => I conversion is a problem. It must be I => ı and i => İ so my simple solution is

    public function title_case_turkish($str){

        $str = str_replace("i", "İ", $str);
        $str = str_replace("I", "ı", $str);

        $str = mb_convert_case($str, MB_CASE_TITLE,"UTF-8");

        return $str;

    }


cataphract at php dot net

12 years ago


This is a variation of mb_convert_case that works only for UTF-8 strings and that will not convert to lowercase anything.

This avoids turning "AAA aaa" into "Aaa Aaa"; it maps "AAA aaa" into ""AAA Aaa" instead.

<?php

function mb_convert_case_utf8_variation($s) {

   
$arr = preg_split("//u", $s, -1, PREG_SPLIT_NO_EMPTY);

   
$result = "";

   
$mode = false;

    foreach (
$arr as $char) {

       
$res = preg_match(

           
'/\p{Mn}|\p{Me}|\p{Cf}|\p{Lm}|\p{Sk}|\p{Lu}|\p{Ll}|'.

           
'\p{Lt}|\p{Sk}|\p{Cs}/u', $char) == 1;

        if (
$mode) {

            if (!
$res)

               
$mode = false;

        }

        elseif (
$res) {

           
$mode = true;

           
$char = mb_convert_case($char, MB_CASE_TITLE, "UTF-8");

        }

       
$result .= $char;

    }

    return

$result;

}

?>


  John Mwaniki /   29 Sep 2021

As a developer, you work with strings of different nature in day-to-day projects. Some may be a word long, a phrase, a sentence, or even comprising thousands of words.

It is easy to work on and change the case on shorter strings manually, eg. you can edit the string and make a sentence begin with an uppercase letter, to change an all uppercase text to a sentence case, etc.

In the case of long strings of texts, this will not be an easy task to accomplish and may take too long. The good news is that most programming languages have a way to easily convert and manipulate the case in a string.

In this article, you will learn how to convert strings to different cases using PHP language.

Converting a string to lowercase in PHP

To change all the alphabetical characters in a string to lowercase, we use the PHP strtolower() function.

Example:

<?php
$string = "Hello World!";
echo strtolower($string);
?>

Output:

hello world!

 

Converting a string to uppercase in PHP

To change all the alphabetical characters in a string to uppercase, we use the PHP strtoupper() function.

Example:

<?php
$string = "Hello World!";
echo strtoupper($string);
?>

Output:

HELLO WORLD!

Converting the first character in a string to uppercase in PHP

To change the first alphabetical characters of a string to uppercase, we use ucfirst() function.

Example:

<?php
$string = "hello world!";
echo ucfirst($string);
?>

Output:

Hello world!

Converting the first character of each word to uppercase in PHP

To change the first character of every word in a string in PHP, we use ucwords() function.

Example:

<?php
$string = "hello world!";
echo ucwords($string);
?>

Output:

Hello World!

Converting the string to sentence case in PHP

All sentences start with an uppercase(capital) letter and end with either a full stop (.), a question mark (?), or an exclamation mark (!).

If our string comprises only one sentence, then converting it to a sentence case is very simple as we only use the ucfirst() function to convert its first character to uppercase.

Example:

<?php
$string = "which programming language do you love most?";
echo ucfirst($string);
?>

Output:

Which programming language do you love most?

However, that will not be the case with a string comprising of multiple sentences.

In such a case:

— We split the string into an array of sentences using the preg_split() function;

— We loop through all the sentences in a for each loop;

— Convert the string characters in each sentence to lower case using the strtolower() function;

— Convert the first character of every sentence to uppercase using the ucfirst() function;

— Concatenate all our sentences to form back the original string, now with a sentence case.

Example:

<?php
$string = "hello world! i am a programmer. i like programming in php.";
$sentences = preg_split('/([.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE); 

$newstring = ""; 
foreach ($sentences as $sentence) { 
 $newsentence = ucfirst(strtolower(trim($sentence)));
 /*
 The above line of code trims white space at the beginning and end of the sentence.. trim()
 Converts it to lower case using strtolower()
 Then converts the first character to upper case using ucfirst()
 Then assigns it to the variable $newsentence
 */
 $newstring .= $newsentence; // Concatenate to the $newstring
 if(preg_match('/([.?!]+)/', $sentence)){
  $newstring .= " "; // Add a space after fullstop, question mark, or exclamation mark
 }
} 
echo $newstring;
?>

Output:

Hello world! I am a programmer. I like programming in php.

From the above example, you can skip the conversion to lower case if you just want all the sentences to start with an uppercase without affecting the cases of other words/characters.

Conclusion

In this article, you have learned how to convert PHP strings to upper case, lower case, the first character of every word to upper case, the first character of the string to upper case, and also how to convert a combination of multiple sentences into sentence case, where every first character of every sentence starts with an upper case.

It is my hope that the article was simple enough to follow along and easy to understand and implement.

To get notified when we add more incredible content to our site, feel free to subscribe to our free email newsletter.

The quickest way is with a bitmask. No clunky string functions or regex. PHP is a wrapper for C, so we can manipulate bits quite easily if you know your logical function like OR, NOT, AND, XOR, NAND, etc..:

function swapCase($string) {
    for ($i = 0; $i < strlen($string); $i++) {
        $char = ord($string{$i});
        if (($char > 64 && $char < 91) || ($char > 96 && $char < 123)) {
            $string{$i} = chr($char ^ 32);
        }
    }
    return $string;
}

This is what changes it:

$string{$i} = chr($char ^ 32);

We take the Nth character in $string and perform an XOR (^) telling the interpreter to take the integer value of $char and swapping the 6th bit (32) from a 1 to 0 or 0 to 1.

All ASCII characters are 32 away from their counterparts (ASCII was an ingenious design because of this. Since 32 is a power of 2 (2^5), it’s easy to shift bits. To get the ASCII value of a letter, use the built in PHP function ord():

ord('a') // 65
ord('A') // 97
// 97 - 65 = 32

So you loop through the string using strlen() as the middle part of the for loop, and it will loop exactly the number of times as your string has letters. If the character at position $i is a letter (a-z (65-90) or A-Z (97-122)), it will swap that character for the uppercase or lowercase counterpart using a bitmask.

Here’s how the bitmask works:

0100 0001 // 65 (lowercase a)
0010 0000 // 32 (bitmask of 32)
--------- // XOR means: we put a 1 if the bits are different, a 0 if they are same.
0110 0001 // 97 (uppercase A)

We can reverse it:

0110 0001 // 97 (A)
0010 0000 // Bitmask of 32
---------
0100 0001 // 65 (a)

No need for str_replace or preg_replace, we just swap bits to add or subtract 32 from the ASCII value of the character and we swap cases. The 6th bit (6th from the right) determines if the character is uppercase or lowercase. If it’s a 0, it’s lowercase and 1 if uppercase. Changing the bit from a 0 to a 1 ads 32, getting the uppercase chr() value, and changing from a 1 to a 0 subtracts 32, turning an uppercase letter lowercase.

swapCase('userId'); // USERiD
swapCase('USERiD'); // userId
swapCase('rot13'); // ROT13

We can also have a function that swaps the case on a particular character:

// $i = position in string
function swapCaseAtChar($string, $i) {
    $char = ord($string{$i});
    if (($char > 64 && $char < 91) || ($char > 96 && $char < 123)) {
        $string{$i} = chr($char ^ 32);
        return $string;
    } else {
        return $string;
    }
}

echo swapCaseAtChar('iiiiiiii', 0); // Iiiiiiii
echo swapCaseAtChar('userid', 4); // userId

// Numbers are no issue
echo swapCaseAtChar('12345qqq', 7); // 12345qqQ

    The PHP functions strtoupper and ucwords capitalise all characters in a string, and the first letter of every word in a string, respectively. However, there exists in the standard PHP library no way of achieving Title Case, which involves capitalising all words except for small words (such as conjunctions) when they are not the first word.

    The following mini-tutorial will provide a solution similar to the one I came up with for displaying thread titles in the SitePoint Forums’ Highlighted Forum Discussions.

    First, we’ll need a list of all the words which we don’t want to capitalise when they are not the first word. The words we should be concerned about are conjunctions (such as and, or), prepositions (in, on) and internal articles (the, a). However, I’m no expert in English grammar so I’ll just call them ‘small words’. Here’s a selection of the ones I use.


    $smallwordsarray = array(
    'of','a','the','and','an','or','nor','but','is','if','then','else','when',
    'at','from','by','on','off','for','in','out','over','to','into','with'
    );

    The explode function in PHP can be used to split any string into an array of strings, using a character as a split character. So if we split with a space character (‘ ‘), we can use explode to split our string into words.


    $words = explode(' ', 'this is a title');

    $words becomes an array of strings, each string representing one word from the original $title. Here it would be equal to array(‘This’, ‘is’, ‘a’, ‘title’).

    We can now operate on each word separately. We need to test each word to determine if it is one of our ‘small words’. If it is not a small word, or it’s the first word, it should be capitalised. To operate on each member of an array in turn, we can use the PHP language construct foreach. To check if a word is one of our small words, we can use in_array


    foreach ($words as $key => $word)
    {
    if (!$key or !in_array($word, $smallwordsarray))
    $words[$key] = ucwords($word);
    }

    Notice here that I assigned the value to $words[$key] and not to $word. The reason for this is that $word was created by the foreach statement. Modifying $word will not cause any change to the original array $words. So I need to modify the entry in the original array $words that corresponds to the current array key.

    By this point, we have an array of all the words in our title. Those words which should be capitalised have been, and all that’s left is to join the words together again into a single string. This can be done with implode, which works in the opposite direction to explode.


    $newtitle = implode(' ', $words);

    Here’s the entire script as a function you’re welcome to use in your application.


    function strtotitle($title)
    // Converts $title to Title Case, and returns the result.
    {
    // Our array of 'small words' which shouldn't be capitalised if
    // they aren't the first word. Add your own words to taste.
    $smallwordsarray = array(
    'of','a','the','and','an','or','nor','but','is','if','then','else','when',
    'at','from','by','on','off','for','in','out','over','to','into','with'
    );

    // Split the string into separate words
    $words = explode(' ', $title);

    foreach ($words as $key => $word)
    {
    // If this word is the first, or it's not one of our small words, capitalise it
    // with ucwords().
    if ($key == 0 or !in_array($word, $smallwordsarray))
    $words[$key] = ucwords($word);
    }

    // Join the words back into a string
    $newtitle = implode(' ', $words);

    return $newtitle;
    }

    Notice that if the input already contains capital letters, those letters will remain. This ensures that letters that must always be capital, such as acronyms, will remain so.

    Try it out with a title, such as


    echo strtotitle("this is a title");

    The result? “This is a Title”.

    As an aside, a quick search on Google found a solution to the same problem in JavaScript. However, it is a nightmare of code – unnecessarily complex. It checks every letter separately! You’d be better off porting my script to JavaScript.

    By the way, here’s a similar solution in ColdFusion.

    Altering the case of a string is very easy with PHP’s four built-in functions:

    1. strtoupper()
    2. strtolower()
    3. ucfirst() and
    4. ucwords().

    The above functions do not work on multibyte strings you should use the multibyte equivalents of those functions:

    1. mb_strtolower()
    2. mb_strtoupper()
    3. mb_convert_case().
    4. mb_ucfirst()

    strtoupper

    //Syntax
    strtoupper(string $string): string

    The strtoupper function converts string characters into upper case.

    <?php
     $string = 'A Sample STRING.';
     echo strtoupper($string);
     //prints: A SAMPLE STRING.

    strtolower

    //Syntax
    strtolower(string $string): string

    The strtolower function lower cases all the characters in a string.

    <?php
     $string = 'A Sample STRING.';
     echo strtolower($string);
     //prints: a sample string.

    ucfirst

    <?php
    //Syntax
    ucfirst(string $string): string

    The ucfirst function capitalizes the first character of a string.

    <?php
     $string = 'a Sample STRING.';
     echo ucfirst($string);
     //prints: A Sample STRING.

    ucwords

    <?php
    //Syntax
    ucwords(string $string, string $separators = " trnfv"): string

    The ucwords function capitalizes the first character of every word in a string.

    <?php
     $string = 'a sample string.';
     echo ucwords($string);
     //Prints: A Sample String.

    The optional $separators contains the word separator characters. See the following example:

    <?php
     //Single separator |
     echo ucwords ('capitalizes|the|first|character of every word', '|');
     //Capitalizes|The|First|Character of every word
    
     //Multiple separator | and space
     echo ucwords ('capitalizes|the|first|character of every word', '| ');
     //Capitalizes|The|First|Character Of Every Word
    

    Change Multibyte String Case

    The native string functions in PHP assume strings are an array of single bytes, so functions strtolower, strtoupper, ucwords and ucfirst will not work on multibyte strings, such as Japanese and Chinese characters. You should use the multibyte equivalents of those functions, such as mb_strtolower, mb_strtoupper and mb_convert_case.

    The multi-byte functions accept another optional parameter for the character encoding. If it is omitted, the internal character encoding value will be used.

    We can set the internal character encoding by using mb_internal_encoding.

    <?php
      mb_internal_encoding('UTF-8');

    By setting up the internal encoding, it is not necessary to provide the encoding parameter for the multibyte functions.

    mb_strtolower

    <?php
    //Syntax:
    mb_strtolower(string $string, ?string $encoding = null): string

    The mb_strtolower function lower cases all the characters in a multibyte string. If the second parameter $encoding is omitted, the internal character encoding value will be used.

    <?php
     $string = 'Ἇ Ђ Б';
     echo mb_strtolower($string);
    
     // Setting character encoding
     echo mb_strtolower($string,'UTF-8');
     //Prints: ἇ ђ б

    mb_strtoupper

    The mb_strtoupper function upper cases all the characters in a multi-byte string.

    <?php
     $string = 'ἇ ђ б';
     echo mb_strtoupper($string);
    
     //Set character encoding
     echo mb_strtoupper($string,'UTF-8');
     //Prints: Ἇ Ђ Б

    mb_convert_case

    The mb_convert_case function convert case on the basis of the Unicode character properties, it can convert any characters that have ‘alphabetic’ property, such as A-umlaut (Ä).

    <?php
     $string = 'Τάχιστη αλώπηξ βαφής ψημένη γη';
     echo mb_convert_case($string, MB_CASE_UPPER);
     //ΤΆΧΙΣΤΗ ΑΛΏΠΗΞ ΒΑΦΉΣ ΨΗΜΈΝΗ ΓΗ
    
     //You also can provide your desired encoding
     echo mb_convert_case($string, MB_CASE_LOWER, 'UTF-8');
     //τάχιστη αλώπηξ βαφής ψημένη γη
    
     echo mb_convert_case($string, MB_CASE_TITLE, 'UTF-8');
     //Τάχιστη Αλώπηξ Βαφής Ψημένη Γη

    Howto capitalize the first character of a multi-byte string

    PHP does not have a mb_ucfirst function but you can use the following custom function as an alternative.

    mb_ucfirst function example

    <?php
     function mb_ucfirst($string, $encoding = null) {
      if (empty($string))
       return $string;
      $encoding = is_null($encoding) ? mb_internal_encoding() : $encoding;
      $firstChr = mb_strtoupper(mb_substr($string, 0, 1,$encoding),$encoding);
      return $firstChr . mb_substr($string, 1, null, $encoding);
    }

    Creating mb_ucfirst function step by step

    This step by step tutorial will elaborate the above mb_ucfirst function.

    Step 1. Create function mb_ucfirst which will accept two parameters, first for the input string and the second for the character encoding. Assign NULL to encoding parameter as default values.

    function mb_ucfirst($string, $encoding = null) {
    
    }

    Step 2. Check for empty string by validating it with empty function. empty function returns false if string value does not exist or equals to FALSE.

    function mb_ucfirst($string, $encoding = null) {
     if (empty($string)) return;
    }

    Step 3. Validate second parameter $encoding with is_null function. is_null function returns true if value is null. If character encoding not provided we’ll assign internal encoding to $encoding parameter using mb_internal_encoding function.

    function mb_ucfirst($string, $encoding = null) {
     if (empty($string)) return $string;
     if (is_null($encoding)) {
      $encoding = mb_internal_encoding();
     }
    }

    Step 4. Extract first character of the string using mb_substr function (similar to substr function but multi byte safe). mb_substr accepts four parameters : $string, $start, $length, $encoding. The $start value 0 and $lenght value 1 return the first character from the string.

    function mb_ucfirst($string, $encoding = null) {
     if (empty($string)) return $string;
     if (is_null($encoding)) {
      $encoding = mb_internal_encoding();
     }
     $firstChr = mb_substr($string, 0, 1,$encoding);
    }

    Step 4. Change first character $firstChr case using mb_strtoupper function.

    function mb_ucfirst($string, $encoding = null) {
     if (empty($string)) return $string;
     if (is_null($encoding)) {
      $encoding = mb_internal_encoding();
     }
     $firstChr = mb_substr($string, 0, 1,$encoding);
     $firstChr = mb_strtoupper($firstChr,$encoding);
    }

    Step 5. Now extract the remaining string (without the first character) from the original string using mb_substr function.

    We’ll use 1 and null for start and length values respectively in mb_substr function, to extract all the remaining characters.

    Note: If NULL is passed in length value the mb_substr function will extract all characters to the end of the string.

    function mb_ucfirst($string, $encoding = null) {
     if (empty($string)) return $string;
     if (is_null($encoding)) {
      $encoding = mb_internal_encoding();
     }
     $firstChr = mb_substr($string, 0, 1,$encoding);
     $firstChr = mb_strtoupper($firstChr,$encoding);
     $remainingString = mb_substr($string, 1, null, $encoding);
    }

    Step 6. Now concate $firstChar and $remainingString with . and return it.

    function mb_ucfirst($string, $encoding = null) {
     if (empty($string)) return $string;
     if (is_null($encoding)) {
      $encoding = mb_internal_encoding();
     }
     $firstChr = mb_substr($string, 0, 1,$encoding);
     $firstChr = mb_strtoupper($firstChr,$encoding);
     $remainingString = mb_substr($string, 1, null, $encoding);
     return $firstChr . $remainingString;
    }

    Working with Strings:

    1. Changing string case
    2. Comparing Strings
    3. Comparing Strings with Natural Order Algorithm
    4. Converting Strings into HTML
    5. Converting HTML Entities and Special Characters
    6. Formatting Strings
    7. Padding Strings
    1. Replacing Newlines with BR Tag and Trimming Whitespaces
    2. Converting character to code and code to character
    3. Repeat and Shuffle a String
    4. Count Characters and Words
    5. Checksum Strings and Files with MD5 and SHA1
    6. Manipulating substrings

    Понравилась статья? Поделить с друзьями:
  • Word cards with picture
  • Word cards with numbers
  • Word cards to make sentences
  • Word cards on ring
  • Word cards for word wall