преобразовать в маленькие буквы php

strtolower

(PHP 4, PHP 5, PHP 7, PHP 8)

strtolower — Преобразует строку в нижний регистр

Описание

Принадлежность того или иного символа к буквенным определяется с учётом текущей локали. Это означает, что, например, в используемой по умолчанию локали «C», символ Ä не будет преобразован.

Список параметров

Возвращаемые значения

Возвращает строку в нижнем регистре.

Примеры

Пример #1 Пример использования strtolower()

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

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 ‘)

Источник

strtoupper

(PHP 4, PHP 5, PHP 7, PHP 8)

strtoupper — Преобразует строку в верхний регистр

Описание

Принадлежность того или иного символа к буквенным определяется с учётом текущей локали. Это означает, что, например, в используемой по умолчанию локали «C», символ ä не будет преобразован.

Список параметров

Возвращаемые значения

Возвращает строку в верхнем регистре.

Примеры

Пример #1 Пример использования strtoupper()

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

User Contributed Notes 16 notes

One might think that setting the correct locale would do the trick with for example german umlauts, but this is not the case. You have to use mb_strtoupper() instead:

Here is how to make the character in upper case, except HTML-entities:

If you only need to extend the conversion by the characters of a certain language, it’s possible to control this using an environment variable to change the locale:

When using UTF-8 and need to convert to uppercase with
special characters like the german ä,ö,ü (didn’t test for french,polish,russian but think it should work, too) try this:

If you can’t find an appropriate locale setting, check your system configuration (locales are a system-wide setting, PHP gets them from the OS). On Windows, locales can be set from the Control Panel; on Linux it depends on your distribution. You can try «sudo dpkg-reconfigure locales» on Debian-based distros, or configure them manually. On Ubuntu Dapper, I had to copy entries over from /usr/share/i18n/SUPPORTED to /var/lib/locales/supported.d/local, then do the dpkg-reconfigure.

After you’re done, restart the web server.

That said, there are special cases where you want to do the conversion manually. In German, for example, the letter ‘ß’ (szlig) only exists as a lower-case character, and so doesn’t get converted by strtoupper. The convential way to express a ‘ß’ in an uppercase string is «SS». This function will take care of this exception (for Latin1 and most of Latin9, at least):

Источник

mb_convert_case

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

mb_convert_case — Производит смену регистра символов в строке

Описание

Список параметров

Строка ( string ) для преобразования.

Возвращаемые значения

Список изменений

Примеры

Пример #1 Пример использования mb_convert_case()

Пример #2 Пример использования mb_convert_case() с нелатинским UTF-8 текстом

Примечания

Дополнительную информацию о свойствах Юникода смотрите по ссылке» http://www.unicode.org/reports/tr21/.

Смотрите также

User Contributed Notes 9 notes

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.

Источник

Сегодня разберем функцию 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

В поле ввода пишем или вставляем текст ПРОПИСНЫМИ! И нажимаем отправить! И вы получите результат! Пока только Русский и английский языки!

Сообщение системы комментирования :

Форма пока доступна только админу. скоро все заработает. надеюсь.

Источник

ucfirst

(PHP 4, PHP 5, PHP 7, PHP 8)

ucfirst — Преобразует первый символ строки в верхний регистр

Описание

Принадлежность того или иного символа к буквенным определяется с учётом текущей локали. Это означает, что, например, в используемой по умолчанию локали «C», символ ä не будет преобразован.

Список параметров

Возвращаемые значения

Возвращает результирующую строку.

Примеры

Пример #1 Пример использования ucfirst()

Смотрите также

User Contributed Notes 35 notes

Simple multi-bytes ucfirst():

A proper Turkish solution;

?>

it also check is mb support enabled or not

This is what I use for converting strings to sentence case:

print sentence_case ( ‘HMM. WOW! WHAT?’ );

// Outputs: «Hmm. Wow! What?»
?>

Here’s a function to capitalize segments of a name, and put the rest into lower case. You can pass the characters you want to use as delimiters.

Implementation of multi-bytes ucfirst for «multiword»-strings (module mbstring is required):

Improved method of capitalizing first characters of sentences.
The first two manipulations (double spaces & all caps) are optional so can be removed without harm.

plemieux’ function did not work for me without passing the encoding to every single mb function (despite ini_set(‘default_charset’, ‘utf-8’) at the top of the script). This is the example that works in my application (PHP 4.3):

For some reason this worked for me.

Mac OS 10.5.1
PHP 5.2.6

Here is the fixed function for Turkish alphabet..

for anyone wanting to ucfirst each word in a sentence this works for me:

For lithuanian text with utf-8 encoding I use two functions (thanks [mattalexxpub at gmail dot com] and Svetoslav Marinov)

My version, converst first letter of the first word in the string to uppercase

public function mb_ucfirst($str) <
$aParts = explode(» «,$str);
$firstWord = mb_convert_case($aParts[0],MB_CASE_TITLE,»UTF-8″);
unset($aParts[0]);

I made a small change. Now it takes care of points in numbers

if you want to ucfirst for utf8 try this one:

( «UTF-8» );
mb_regex_encoding ( «UTF-8» );

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»
);

Using this function for Turkish language is won’t work because of multi-byte characters. But you can use some tricks:

here is how mb_ucfirst should be implemented in userland

@adefoor, Ken and Zee

This is a simple code to get all the ‘bad words’, stored in a database, out of the text. You could use str_ireplace but since that’s installed on PHP5 only, this works as well. It strtolowers the text first then places capitals with ucfirst() where it thinks a capital should be placed, at a new sentence. The previous sentence is ended by ‘. ‘ then.

Ah, the last code were spoiled, here is the fixed one:

?>

So, this function changes also other letters into uppercase, ucfirst() does only change: a-z to: A-Z.

Note: the return for this function changed in versions 4.3 when a string is passed of length 0. In 4.3 a string of length 0 is returned.

Results for 4.3:
string(0) «» string(4) «Owen»

In the event you sort of need multiple delimiters to apply the same action to, you can preg_replace this «second delimiter» enveloping it with your actual delimiter.

A for instance, would be if you wanted to use something like Lee’s FormatName function in an input box designed for their full name as this script was only designed to check the last name as if it were the entire string. The problem is that you still want support for double-barreled names and you still want to be able to support the possibility that if the second part of the double-barreled name starts with «mc», that it will still be formatted correctly.

This example does a preg_replace that surrounds the separator with your actual delimiter. This is just a really quick alternative to writing some bigger fancier blah-blah function. If there’s a shorter, simpler way to do it, feel free to inform me. (Emphasis on shorter and simpler because that was the whole point of this.) 😀

Here’s the example. I’ve removed Lee’s comments as not to confuse them with my own.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *