PHP mb_convert_case() Function

What is PHP mb_convert_case() Function?

If you want to convert the case of a multibyte string, use mb_convert_case() function.

Syntax:

mb_convert_case(string, mode, encoding)

Parameters:

The Function has 2 required parameters and 1 optional parameter-

string (Required): It specifies the input string

mode (Optional): It specifies the conversion mode which indicates how the conversion will be applied. The modes are some predefined constants. See the modes below with examples-

  • MB_CASE_UPPER – It converts the entire string to uppercase. Check example 1.
  • MB_CASE_LOWER – It converts the entire string to lowercase. Check example 2.
  • MB_CASE_TITLE – It converts the first letter of each word to uppercase. Check example 3.
  • MB_CASE_UPPER_SIMPLE – It converts the entire string to uppercase using simple rules.
  • MB_CASE_LOWER_SIMPLE – It converts the entire string to lowercase using simple rules.
  • MB_CASE_TITLE_SIMPLE – It converts the first letter of each word to uppercase using simple rules.
  • MB_CASE_FOLD – it is used for case-insensitive search.

Difference between MB_CASE_LOWER and MB_CASE_ LOWER_SIMPLE mode

MB_CASE_LOWER performs a full lowercase conversion and the resulting string’s length might be different than the original string. On the other hand, MB_CASE_LOWER_SIMPLE performs a simple lowercase conversion and the resulting string’s length is same as the original string’s length.

encoding (Optional): It specifies the character encoding system to use. The character encoding system encodes the string. If you omit this parameter or mention it NULL, the default character encoding system will be used. But, the default encoding may not encode the string properly (See exercise 3). You can find the default character encoding system in php.ini file in “default_charset = “ setting.

Return Values:

The function returns the converted string based on the specified mode.

Examples:

Example 1:

<?php
$string = "schools of web";
echo mb_convert_case($string, MB_CASE_UPPER, "UTF-8");
?>

Output:

SCHOOLS OF WEB

Example 2:

<?php
$string = "Schools of Web";
echo mb_convert_case($string, MB_CASE_LOWER, "UTF-8");
?>

Output:

schools of web

Example 3:

<?php
$string = "schools of web";
echo mb_convert_case($string, MB_CASE_TITLE, "UTF-8");
?>

Output:

Schools Of Web

Best Practices on mb_convert_case() Function:

While encoding is optional, it’s best practice to explicitly mention its value. Example “UTF-8”.

Notes on mb_convert_case() Function:

This function is particularly useful when working with non-ASCII characters.

PHP Version Support:

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

Summary: PHP mb_convert_case() Function

The mb_convert_case() is a built-in multi byte string function in PHP. Use this function for safe case conversion of a multi byte string.

Reference:

https://www.php.net/manual/en/function.mb-convert-case.php