- Converting String to Lowercase in PHP
- Introduction:
- Method 1: Using strtolower() function
- Output:
- Method 2: Using mb_strtolower() for Multibyte Support
- Output:
- Method 3: Using strtr() with a custom mapping
- Output:
- Method 4: Using a Regular Expression
- Output:
- Conclusion:
- Related Post
- Замена регистра в строках PHP
- Проверка, является ли буква прописной или строчной
- Первая заглавная буква
- Для UTF-8:
- Первая строчная
- Для UTF-8:
- Все заглавные буквы
- Для UTF-8:
- Все строчные буквы
- Для UTF-8:
- Заглавная буква в каждом слове
- Для UTF-8:
- Инверсия регистра
- Комментарии 1
- strtolower
- Parameters
- Return Values
- Changelog
- Examples
- Notes
- See Also
- User Contributed Notes 16 notes
- How to change case in PHP strings to upper, lower, sentence, etc
- Converting a string to lowercase in PHP
- Converting a string to uppercase in PHP
- Converting the first character in a string to uppercase in PHP
- Converting the first character of each word to uppercase in PHP
- Converting the string to sentence case in PHP
- Conclusion
- You May Also Like:
Converting String to Lowercase in PHP
In this blog, we will learn how to convert strings to lowercase. We provide multiple methods to achieve this, ranging from basic built-in functions like strtolower() to more advanced techniques involving regular expressions and multibyte support with mb_strtolower().
Introduction:
In PHP, there are several methods available for lowercase conversion. In this blog, we will explore multiple approaches to convert strings to lowercase in PHP, providing detailed explanations and examples for each method.
Method 1: Using strtolower() function
The simplest and most straightforward method to convert a string to lowercase in PHP is by using the built-in strtolower() function. This function takes a string as input and returns the same string with all characters converted to lowercase. Here’s an example of how to use this function:
Output:
The strtolower() function performs a case-insensitive conversion, meaning that all uppercase characters in the input string will be converted to their lowercase counterparts.
Method 2: Using mb_strtolower() for Multibyte Support
The strtolower() function is suitable for most cases; however, it may not handle multibyte characters correctly. For scenarios involving multibyte character sets like UTF-8, we should use the mb_strtolower() function instead. Here’s an example:
Output:
The mb_strtolower() function supports multibyte characters, making it more reliable when working with different languages and character sets.
Method 3: Using strtr() with a custom mapping
Another approach to convert strings to lowercase is by using the strtr() function with a custom character mapping. We can define an array where each uppercase character maps to its lowercase counterpart, and then use strtr() to perform the conversion. Here’s an example:
'a', 'B' => 'b', 'C' => 'c', 'D' => 'd', 'E' => 'e', 'F' => 'f', 'G' => 'g', 'H' => 'h', 'I' => 'i', 'J' => 'j', 'K' => 'k', 'L' => 'l', 'M' => 'm', 'N' => 'n', 'O' => 'o', 'P' => 'p', 'Q' => 'q', 'R' => 'r', 'S' => 's', 'T' => 't', 'U' => 'u', 'V' => 'v', 'W' => 'w', 'X' => 'x', 'Y' => 'y', 'Z' => 'z' ); $lowercaseString = strtr($inputString, $customMapping); echo $lowercaseString; ?>
Output:
The strtr() function replaces each character in the input string that matches the keys of the custom mapping array with their corresponding values, effectively converting the string to lowercase.
Method 4: Using a Regular Expression
Regular expressions provide a powerful toolset for string manipulation. We can utilize a regular expression to replace all uppercase letters with their lowercase counterparts. Here’s an example:
, $inputString); echo $lowercaseString; ?>
Output:
The preg_replace() function performs a regular expression search for uppercase letters ( [A-Z] ) and replaces them using the anonymous function, which converts each matched character to lowercase.
Conclusion:
In this blog, we explored multiple methods to convert strings to lowercase in PHP. We started with the built-in strtolower() function and discussed its limitations with multibyte characters, leading us to the use of mb_strtolower() for better support. We then learned how to create a custom character mapping with strtr() and use regular expressions for case conversion.
Related Post
Замена регистра в строках PHP
Список PHP-функций для изменения регистра символов в строках и примеры их использования.
Проверка, является ли буква прописной или строчной
Функция ctype_upper($string) – определяет, являются ли все буквы в строке в верхнем регистре.
$str = 'Ы'; if (ctype_upper($str)) < echo 'Заглавная'; >else
Вариант для кириллицы в кодировке UTF-8:
$str = 'Ы'; if (mb_strtolower($str) !== $str) < echo 'Заглавная'; >else < echo 'строчная'; >// Выведется «Заглавная»
Пример определения регистра для первой буквы в строке:
$text = 'Привет мир!'; $chr = mb_substr($text, 0, 1); if (mb_strtolower($chr) !== $chr) < echo 'Заглавная'; >else < echo 'строчная'; >// Выведется «Заглавная»
Первая заглавная буква
ucfirst($string) — преобразует первый символ строки в верхний регистр.
$text = 'привет Мир!'; echo ucfirst($text);
Для UTF-8:
if(!function_exists('mb_ucfirst')) < function mb_ucfirst($str) < $fc = mb_strtoupper(mb_substr($str, 0, 1)); return $fc . mb_substr($str, 1); >> $text = 'привет Мир!'; echo mb_ucfirst($text); // Привет Мир!
Первая строчная
ucfirst($string) — преобразует первый символ строки в верхний регистр.
$text = 'Привет Мир!'; echo lcfirst($text);
Для UTF-8:
if(!function_exists('mb_lcfirst')) < function mb_lcfirst($str) < $fc = mb_strtolower(mb_substr($str, 0, 1)); return $fc . mb_substr($str, 1); >> $text = 'Привет Мир!'; echo mb_lcfirst($text); // привет Мир!
Все заглавные буквы
Для UTF-8:
$text = 'привет Мир!'; echo mb_strtoupper($text); // ПРИВЕТ МИР!
Все строчные буквы
$text = 'Привет Мир!'; echo strtolower($text);
Для UTF-8:
$text = 'Привет Мир!'; echo mb_strtolower($text); // привет мир!
Заглавная буква в каждом слове
$text = 'привет мир!'; echo ucwords($text);
Для UTF-8:
if(!function_exists('mb_ucwords')) < function mb_ucwords($str) < $str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8"); return ($str); >> $text = 'привет мир!'; echo mb_ucwords($text); // Привет Мир!
Инверсия регистра
function mb_flip_case($string) < $characters = preg_split('/(?$char) < if (mb_strtolower($char, "UTF-8") != $char) < $char = mb_strtolower($char, 'UTF-8'); >else < $char = mb_strtoupper($char, 'UTF-8'); >$characters[$key] = $char; > return implode('', $characters); > $text = 'Привет Мир!'; echo mb_flip_case($text); // пРИВЕТ мИР!
Комментарии 1
function invertCase($text)
$string = »;
/*
Решение №1
$mb_strlen = mb_strlen($text);
$i = $mb_strlen;
while ($i > 0) $i—;
$char = mb_substr($text, $i, 1);
$char = (mb_strtolower($char) === $char) ? mb_strtoupper($char) : mb_strtolower($char);
$string = $char.$string;
>
*/
// Решение №2
$arr = mb_str_split($text, 1);
foreach ($arr as $char) $char = (mb_strtolower($char) === $char) ? mb_strtoupper($char) : mb_strtolower($char);
$string .= $char;
>
return $string;
>
Авторизуйтесь, чтобы добавить комментарий.
strtolower
Returns string with all ASCII alphabetic characters converted to lowercase.
Bytes in the range «A» (0x41) to «Z» (0x5a) will be converted to the corresponding lowercase letter by adding 32 to each byte value.
This can be used to convert ASCII characters within strings encoded with UTF-8, since multibyte UTF-8 characters will be ignored. To convert multibyte non-ASCII characters, use mb_strtolower() .
Parameters
Return Values
Returns the lowercased string.
Changelog
Version | Description |
---|---|
8.2.0 | Case conversion no longer depends on the locale set with setlocale() . Only ASCII characters will be converted. |
Examples
Example #1 strtolower() example
$str = «Mary Had A Little Lamb and She LOVED It So» ;
$str = strtolower ( $str );
echo $str ; // Prints mary had a little lamb and she loved it so
?>?php
Notes
Note: This function is binary-safe.
See Also
- strtoupper() — Make a string uppercase
- ucfirst() — Make a string’s first character uppercase
- ucwords() — Uppercase the first character of each word in a string
- mb_strtolower() — Make a string lowercase
User Contributed Notes 16 notes
strtolower(); doesn’t work for polish chars
the best solution — use mb_strtolower()
for cyrillic and UTF 8 use mb_convert_case
$string = «Австралия» ;
$string = mb_convert_case ( $string , MB_CASE_LOWER , «UTF-8» );
echo $string ;
the function arraytolower will create duplicate entries since keys are case sensitive.
$array = array( ‘test1’ => ‘asgAFasDAAd’ , ‘TEST2’ => ‘ASddhshsDGb’ , ‘TeSt3 ‘ => ‘asdasda@asdadadASDASDgh’ );
$array = arraytolower ( $array );
?>
/*
Array
(
[test1] => asgafasdaad
[TEST2] => ASddhshsDGb
[TeSt3] => asdasda@asdadadASDASDgh
[test2] => asddhshsdgb
[test3] => asdasda@asdadadasdasdgh
)
*/
function arraytolower ( $array , $include_leys = false )
if( $include_leys ) <
foreach( $array as $key => $value ) <
if( is_array ( $value ))
$array2 [ strtolower ( $key )] = arraytolower ( $value , $include_leys );
else
$array2 [ strtolower ( $key )] = strtolower ( $value );
>
$array = $array2 ;
>
else <
foreach( $array as $key => $value ) <
if( is_array ( $value ))
$array [ $key ] = arraytolower ( $value , $include_leys );
else
$array [ $key ] = strtolower ( $value );
>
>
return $array ;
>
?>
which when used like this
$array = $array = array( ‘test1’ => ‘asgAFasDAAd’ , ‘TEST2’ => ‘ASddhshsDGb’ , ‘TeSt3 ‘ => ‘asdasda@asdadadASDASDgh’ );
$array1 = arraytolower ( $array );
$array2 = arraytolower ( $array , true );
print_r ( $array1 );
print_r ( $array2 );
?>
will give output of
Array
(
[test1] => asgafasdaad
[TEST2] => asddhshsdgb
[TeSt3] => asdasda@asdadadasdasdgh
)
Array
(
[test1] => asgafasdaad
[test2] => asddhshsdgb
[test3] => asdasda@asdadadasdasdgh
)
When you’re not sure, how the current locale is set, you might find the following function useful. It’s strtolower for utf8-formatted text:
function strtolower_utf8 ( $inputString ) $outputString = utf8_decode ( $inputString );
$outputString = strtolower ( $outputString );
$outputString = utf8_encode ( $outputString );
return $outputString ;
>
?>
It’s not suitable for every occasion, but it surely gets in handy. I use it for lowering German ‘Umlauts’ like ä and ö.
function strtolower_slovenian ( $string )
$low =array( «Č» => «č» , «Ž» => «ž» , «Š» => «š» );
return strtolower ( strtr ( $string , $low ));
>
How to change case in PHP strings to upper, lower, sentence, etc
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.
Converting a string to uppercase in PHP
To change all the alphabetical characters in a string to uppercase, we use the PHP strtoupper() function.
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.
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.
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.
Which programming language do you love most?
However, that will not be the case with a string comprising of multiple sentences.
— 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.
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.