php string to lowercase
PHP: Convert a string into lowercase.
This is a short guide on how to convert a string into lowercase using PHP.
To do this, we can either use the function strtolower or the function mb_strtolower.
Using the strtolower function.
Using the strtolower function is pretty straight forward. Simply pass your string into the function and it will return that string in a lowercase format.
As you can see, the strtolower function is pretty simple to use.
However, there is one issue with it: It cannot convert special characters.
Any special or accented characters will be converted into garbled replacement characters.
Take a look at following example:
In the code above, we attempted to convert an U-umlaut character into lowercase. However, this will fail, as strtolower is unable to convert special characters like the U-umlaut or the A-umlaut.
As a result, we end up with a string that looks like this.
As you can see, our special character looks like a question mark inside a diamond. This “diamond” is a replacement character.
When you see this character, it means that the system was unable to find the correct symbol. In this case, strtolower could not find the correct lowercase symbol for our U-umlaut character.
To solve this issue, we will need to use the mb_strtolower function instead.
Converting special characters into lowercase.
mb_strtolower is a multi-byte safe function that can convert special characters into lower case. Basically, it can handle any special character that has an “alphabetic” property.
An example of mb_strtolower in use.
If you run the PHP snippet above, you will get the following output:
As you can see in the screenshot above, our U-umlaut has been converted into its lowercase equivalent.
Here is another example.
In this case, we were able to convert multiple special characters into their lowercase equivalents.
Perfect! Hopefully, you found this tutorial useful!
Сегодня разберем функцию strtolower, которая преобразует строку в нижний регистр. Т.е. все буквы делает строчными в php. Попробуем разобраться в ошибках связанных с функцией strtolower, примеры strtolower, напишем свою функцию для кириллицы преобразующие большие буквы в маленькие, но не только о strtolower, но и коснемся mb-strtolower.
Естественно нужно начать с определения даннйо функции:
Все о функции strtolower
Что такое strtolower
Синтаксис функции strtolower
Разбор синтаксиса функции strtolower
Использование strtolower:
Самое удобное, поместить в переменную текст, который пропускается через функцию и получается соответствующая строка.
Ну и далее оборачиваем переменную функцией strtolower:
И выводим результат с помощью echo
Пример использования strtolower для латиницы:
Далее применим к данной строке strtolower с использованием функции echo :
Результат применения strtolower к английскому тексту, который написан «ПРОПИСНЫМИ»
После этого можем переходить к кириллице!
Использование strtolower для кириллицы:
Опять поступаем со строкой, как в выше идущем пункте:
Расположим данный вывод прямо здесь и получим:
Мы видим, что ничего у нас не произошло…
Почему не сработала функция strtolower
Насколько я понимаю, что проблема в данном случае с кодировкой utf-8 для кириллицы! Дело в том, что кириллица в данной кодировке имеет не один символ а два. и strtolower просто не понимает, что от него хотят.
Чтобы показать в живую, чем отличается кириллица от латиницы:
Strtolower не работает для кириллицы
Но если например мы будем использовать данную функцию в таком виде:
То получим такой результат:
��� �������� �����, ������� ����� �������������� ��������� ���������� Чтобы mb_strtolower заработала с кириллицей UTF-8 ей нужно придать кодировку, таким образом:
Смотрим, что у нас в итоге получилось:
это тестовый текст, который будет иллюстрировать поведение стролловер
Собственная функция Strtolower для кириллицы!
Сталкивались с Strtolower для кириллицы!? Или может вы использовали mb-strtolower для кириллицы!? Эти функции работали и как впечатление!?
Когда в последний раз меня вывела из себя функция mb-strtolower – оказывается – эту хрень еще и подключать надо! Какая важная фифа, что она может даже быть и отключенная! Не то, что я не могу разобраться, как её включить – но просто это так достало, что просто нет тех слов цензурных слов, которые могли бы выразить все то, что я им хочу сказать!
Сделаем собственную функцию Strtolower для кириллицы!
Нам нужна такая функция Strtolower для кириллицы, чтобы она работала всегда и везде и чтобы больше никогда я не встречался с этой проблемой – мы просто напишем собственную функцию Strtolower для кириллицы!
Нам понадобится массив, который представляет из себя ключ – Большая кириллическая буква(верхний регистр = «ПРОПИСНЫЕ»), значение маленькая кириллическая буква(нижний регистр = «строчные»)
Еще нам понадобится функция strtr – которая преобразует найденные ключи в значения!
2). Поместим наш тестовый текст с прописными буквами в переменную
И обработаем дальше уже нашей функцией Strtolower для кириллицы
Результат работы собственной функции для кириллицы!
Собственная функция Strtolower для кириллицы и латиницы!
Пойдем дальше! Чем каждый раз вспоминать,какая функция работает там, работает сям! Сделаем функцию для кириллицы и латиницы, дарю:
Теперь давайте испытаем, сразу на двух текстах. что мы сделаем!?
Выведем наши текста таикм образом:
Результат работы собственной функции strollower
Онлайн функция Strtolower для текста!
Теперь на нашем сайте вы можете привести весь текст, который так или иначе написан с включением больших(прописных) букв, превратить в текст написанный строчными, т.е. маленькими!
Как работает онлайн Strtolower
В поле ввода пишем или вставляем текст ПРОПИСНЫМИ! И нажимаем отправить! И вы получите результат! Пока только Русский и английский языки!
Сообщение системы комментирования :
Форма пока доступна только админу. скоро все заработает. надеюсь.
strtolower
(PHP 4, PHP 5, PHP 7, PHP 8)
strtolower — Make a string lowercase
Description
Returns string with all alphabetic characters converted to lowercase.
Note that ‘alphabetic’ is determined by the current locale. This means that e.g. in the default «C» locale, characters such as umlaut-A (Ä) will not be converted.
Parameters
Return Values
Returns the lowercased string.
Examples
Example #1 strtolower() example
Notes
See Also
User Contributed Notes 16 notes
strtolower(); doesn’t work for polish chars
for cyrillic and UTF 8 use mb_convert_case
//output is: австралия
?>
the function arraytolower will create duplicate entries since keys are case sensitive.
I prefer this method
Array
(
[test1] => asgafasdaad
[TEST2] => asddhshsdgb
[TeSt3] => asdasda@asdadadasdasdgh
)
Array
(
[test1] => asgafasdaad
[test2] => asddhshsdgb
[test3] => asdasda@asdadadasdasdgh
)
echo fullLower ( «Ã É Ò Õ ÚÙÛ» );
//results ã é ò õ úùû
//adapted from fullUpper on strtoupper manual
?>
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:
If you’re considering using the below unhtmlentities function from phpContrib, I would suggest this one as an alternative:
There’s a ucfirst «function» to make the first character uppercase, but there’s no «lcfirst» function to make the first character lowercase. Here’s my own code to accomplish this.
I found this particularly useful for generating XML nodes with the Reflection class.
Heres a small function I wrote to stop people from submitting data that is ALL IN CAPS SO THEY CAN GET MORE ATTENTION THAT THE REST OF THE USER SUBMITTED DATA on my website 🙂 If you can make it better, by all means do so. This function splits up words delimited by a space, and makes only the first letter of each word capitalized. You can easily modify it so it’s only the very first word of the string. I’ve also added some exceptions so you don’t make things like roman numerals look like «Iii» or «Xcmii» or something.
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»
);
To do case insensitive comparisons in a database, strtolower() can be a quick and dirty solution:
$Sql = «SELECT * FROM tablename WHERE LOWER(column_name) = ‘».strtolower($my_var).»‘»;
the strtolower version to support most amount of languages including russian, french and so on:
To convert an entire array to lower, I prefer this method;
If you ever need to strtolower a string with href tags on it and doesn’t want to mess with the characters inside a tag, this is for you.
?>
this:
echo loweroutsidetags(‘aALalala ‘)
PHP String to Uppercase, Lowercase & First Letter Uppercase
PHP converts string to lowercase and uppercase. In this tutorial, we will show you, how to convert string to uppercase and how to convert string to lowercase and how to convert the uppercase first letter of each word in PHP with its definition, syntax, parameters, and examples.
1. PHP convert string to lowercase
You can use the php inbuilt function strtolower() for convert string to lowercase.
PHP strtolower() Function
strtolower() is a inbuilt PHP function, which is used to convert string to lowercase.
Note:- This function accept only one parameter as string.
Syntax of this function is:
Example for convert string to lowercase
Let’s take an example, in this example, we have a one-string and we will use the strtolower() function to convert string to lowercase.
The output of the above code is:- ” hello developers, have good day! “
2. PHP convert string to uppercase
You can use the PHP inbuilt function strtoupper() for convert string to uppercase.
PHP strtoupper() Function
strtoupper() is an inbuilt PHP function, which is used to convert string to strtoupper.
Note:- This function accepts only one parameter as a string.
Syntax of this function is:
Example for convert string to uppercase
Let’s take an example, in this example, we have a one-string and we will use the strtoupper() function to convert string to uppercase.
The output of the above code is:- “HELLO DEVELOPERS, HAVE GOOD DAY!”
3. PHP uppercase first letter of each word
You can use the PHP inbuilt function ucwords() for convert uppercase first letter of each word.
PHP ucwords() Function
ucwords() is an inbuilt PHP function, which is used to convert the first letter of each word in a string to uppercase.
Syntax of this function is:
Example for php uppercase first letter of each word
Let’s take an example, we have a one-string and we will use the ucwords() function to uppercase the first letter of each word.
The output of the above code is: ” Hello Developers, Have Good Day! “
strtolower
strtolower — Make a string lowercase
Description
Returns string with all alphabetic characters converted to lowercase.
Note that ‘alphabetic’ is determined by the current locale. This means that in i.e. the default «C» locale, characters such as umlaut-A (Ä) will not be converted.
Parameters
Return Values
Returns the lowercased string.
Examples
Example #1 strtolower() example
Notes
See Also
Коментарии
Heres a small function I wrote to stop people from submitting data that is ALL IN CAPS SO THEY CAN GET MORE ATTENTION THAT THE REST OF THE USER SUBMITTED DATA on my website 🙂 If you can make it better, by all means do so. This function splits up words delimited by a space, and makes only the first letter of each word capitalized. You can easily modify it so it’s only the very first word of the string. I’ve also added some exceptions so you don’t make things like roman numerals look like «Iii» or «Xcmii» or something.
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»
);
To do case insensitive comparisons in a database, strtolower() can be a quick and dirty solution:
$Sql = «SELECT * FROM tablename WHERE LOWER(column_name) = ‘».strtolower($my_var).»‘»;
There’s a ucfirst «function» to make the first character uppercase, but there’s no «lcfirst» function to make the first character lowercase. Here’s my own code to accomplish this.
If you’re considering using the below unhtmlentities function from phpContrib, I would suggest this one as an alternative:
If you ever need to strtolower a string with href tags on it and doesn’t want to mess with the characters inside a tag, this is for you.
?>
this:
echo loweroutsidetags(‘aALalala ‘)
will give:
aalalala
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:
echo fullLower ( «Ã É Ò Õ ÚÙÛ» );
//results ã é ò õ úùû
//adapted from fullUpper on strtoupper manual
?>
the function arraytolower will create duplicate entries since keys are case sensitive.
I prefer this method
Array
(
[test1] => asgafasdaad
[TEST2] => asddhshsdgb
[TeSt3] => asdasda@asdadadasdasdgh
)
Array
(
[test1] => asgafasdaad
[test2] => asddhshsdgb
[test3] => asdasda@asdadadasdasdgh
)
for cyrillic and UTF 8 use mb_convert_case
//output is: австралия
?>
the strtolower version to support most amount of languages including russian, french and so on:
strtolower(); doesn’t work for polish chars
To convert an entire array to lower, I prefer this method;
When the locale is set to «utf8» or «C» I can’t get strtolower() to convert accented characters encoded as UTF-8, so here is my workaround.
print( tolower ( ‘DÉJÀ-VU’ )); // prints déjà-vu
?>
Change the language-country codes if you want some language other than French.