- 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
- Related Articles
- Замена регистра в строках 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
- PHP strtolower() Function
- Syntax
- Parameter Values
- Technical Details
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
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.
Related Articles
Замена регистра в строках 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 ));
>
PHP strtolower() Function
The strtolower() function converts a string to lowercase.
Note: This function is binary-safe.
- strtoupper() — converts a string to uppercase
- lcfirst() — converts the first character of a string to lowercase
- ucfirst() — converts the first character of a string to uppercase
- ucwords() — converts the first character of each word in a string to uppercase
Syntax
Parameter Values
Technical Details
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.