php первую букву в нижний регистр
Php первую букву в нижний регистр
lcfirst — Преобразует первый символ строки в нижний регистр
Описание
Принадлежность того или иного символа к буквенным определяется с учетом текущей локали. Это означает, что, например, в используемой по умолчанию локали «C», символ ä не будет преобразован.
Список параметров
Возвращаемые значения
Возвращает результирующую строку.
Примеры
Пример #1 Пример использования lcfirst()
Смотрите также
Вступление
Преобразование букв
Задача: преобразовать первую букву в строке и все первые буквы во всех словах в строке.
Английские буквы
С английскими буквами в стандартно-используемых кодировках (UTF-8 и Windows-1251) проблем не возникает.
Результат на экране
First letters
First Letters
Кириллица и Windows-1251
С кириллицей в Windows-1251 проблем так же не должно возникнуть.
Результат на экране
Первые буквы
Первые Буквы
Кириллица и UTF-8
С кириллицей в юникоде функции ucfirst() и ucwords() не справятся и преобразований не произойдет.
Результат на экране
первые буквы
первые буквы
Первые буквы
Первые Буквы
Многие люди ищут данную информацию по запросам:
На самом деле как только люди не ищут ответ на этот элементарный вопрос.
Но тем не менее, если вы это ищите, то ответ вы можете найти в данной статье.
На самом деле привести первую буквы к нижнему регистру можно с помощью встроенной функции lcfirst.
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.
ucwords
(PHP 4, PHP 5, PHP 7, PHP 8)
ucwords — Преобразует в верхний регистр первый символ каждого слова в строке
Описание
Список параметров
Необязательный параметр separators содержит символы разделителей слов.
Возвращаемые значения
Возвращает модифицированную строку.
Примеры
Пример #1 Пример использования ucwords()
Пример #2 Пример ucwords() с заданным разделителем
Пример #3 Пример использования ucwords() с дополнительными разделителями
Примечания
Замечание: Функция зависит от локали и будет обрабатывать ввод в соответствии с текущим установленным языковым стандартом. Однако она работает только с однобайтовыми наборами символов. Если вам нужно использовать многобайтовые символы (большинство языков, не входящих в Западную Европу), обратите внимание на модули multibyte или intl вместо нее.
Замечание: Эта функция безопасна для обработки данных в двоичной форме.
Смотрите также
User Contributed Notes 28 notes
My quick and dirty ucname (Upper Case Name) function.
//PRINTS:
/*
Jean-Luc Picard
Miles O’Brien
William Riker
Geordi La Forge
Beverly Crusher
*/
?>
You can add more delimiters in the for-each loop array if you want to handle more characters.
Para formatar nomes em pt-br:
Some recipes for switching between underscore and camelcase naming:
UTF-8 Title Case that works for me even with hyphens involved!
$str = ‘ĐaaČaa-AAAaaa, BBbb’;
$str = mb_convert_case($str, MB_CASE_TITLE, «UTF-8»);
echo($str): ‘Đaačaa-Aaaaaa, Bbbb’
In the function ucsmart() posted by ieure at php dot net on 04-Dec-2005 11:57, I found a similar problem in this function to what he found in igua’s.
Actually, it did end up changing the content for me (php 5.0.4) in the way that this function escapes a single quotation (apostrophe) in the MIDDLE of a word.
The fix is simple however, and merely requires fine-tuning the regular expression:
This will not escape a single quotation mark which occurs in the middle of a word. Though, you may find that might need to add other characters inside the regular expression if you use other special characters inside your words and if you get funky output.
It’s a great expression though! Simple, yet very powerful. Kudos!
Features:
— multi byte compatible
— handles multiple delimiters
Relating to the mb_ucwords() function posted by Anonymous. In order for this to actually be multi-byte compliant, you would also need to use mb_substr() and mb_strlen() instead of substr and strlen respectively.
Here it is corrected and extended even further to allow multiple word separators and a list of exceptions to correct after title casing. It’s a bit tedious and inelegant, but things frequently are when dealing with human languages.
function mb_ucwords($str) <
$exceptions = array();
$exceptions[‘Hp’] = ‘HP’;
$exceptions[‘Ibm’] = ‘IBM’;
$exceptions[‘Gb’] = ‘GB’;
$exceptions[‘Mb’] = ‘MB’;
$exceptions[‘Cd’] = ‘CD’;
$exceptions[‘Dvd’] = ‘DVD’;
$exceptions[‘Usb’] = ‘USB’;
$exceptions[‘Mm’] = ‘mm’;
$exceptions[‘Cm’] = ‘cm’;
// etc.
Turkish character with the ucwords function.
echo ucwords_tr ( ‘ŞEKardi ŞEMŞİYE ĞELENÖ ÖMER’ ); // Şekardi Şemşiye Ğelenö Ömer
echo ucwords_tr ( ‘şEKER iMSAK şÖLEN’ ); // Şeker İmsak Şölen
To avoid this i use a small function adding and deleting blanks behind these chars, and using ucwords() in between:
ucwords for UTF-8 strings:
«ieure at php dot net», your idea is pure poetry!
// captialize all first letters
$str = preg_replace(‘/\\b(\\w)/e’, ‘strtoupper(«$1»)’, strtolower(trim($str)));
ucwords for human names in Brazil.
ucwords personalizada para nomes próprios brasileiros.
Thanks a lot brother.
I tested it with a few variations. It works perfectly. Its really great and simple usage of the existing functions. It would be glad to all PHP folks and good to PHP if these kind of functions will be in PHP library on upcoming releases.
= «mark-yves robert» ;
$name2 = «mark-yves robert-bryan» ;
echo ‘
Name 2 (mark-yves robert-bryan)
?>
Proud to be a PHP enthusiast always 🙂
A very easy way to convert to title case:
function titleCase($string)
<
return ucwords(strtolower($string));
>
$myString = «SOME TEXT»;
//will print, «My Text»
Here is a function to capitalize a last name, accounting for hyphens, apostrophes, «Mc» and «Mac»:
This seems to be what people want:
[ed note: fixed the code to be correct]
The code posted above by Joerg Krause only works for a string which ends with one of the delimiters. A possible fix is:
I did the same thing as Catalin, but for French names.
Here’s what I’m doing :
This complies with the French rules for capitalization in names.
Sample results :
-d’Afoo Bar
-de Foo Bar
-O’Foo Bar
-Foo’bar
Based on code sample originally posted by «Anonymous» on 2005-12-14. The /e modifier is no longer supported by preg_replace(). Rewritten to use preg_replace_callback() instead. Tested with PHP 7.3.
// Trim whitespace and convert to lowercase
$str = strtolower(trim($string));
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 ‘)
Делаем первую букву в строке заглавной на PHP/jQuery/CSS
Зачастую в спешке при добавлении материалов на сайт или, например, создании новой темы на форуме пользователь может начать писать предложение (название) с маленькой (строчной) буквы. Это в какой-то степени является ошибкой.
Я покажу несколько вариантов решения этой задачи: PHP и CSS подойдут больше для уже опубликованных материалов, когда как jQuery сможет исправить положение еще до публикации.
Первая буква строки в верхнем регистре на PHP
На PHP существует функция под названием «ucfirst», которая как раз преобразует первый символ строки в верхний регистр, но минус ее в том, что она не совсем корректно работает с кириллицей.
Для этого мы напишем свою небольшую функцию. Реализация будет выглядеть следующим образом:
В таком варианте мы получим предложение, которое начинается с большой буквы, что, собственно говоря, нам и необходимо.
Первая буква строки в верхнем регистре на CSS
Этот метод визуально (то есть в исходном коде сайта предложения будут выглядеть как есть) также преобразует первый символ в верхний регистр.
С помощью псевдоэлемента «first-letter» и свойства «text-transform» мы задали оформление для каждой первой буквы параграфа.
Первая буква строки в верхнем регистре на jQuery
Как я уже говорил ранее, этот способ преобразования лучше всего подойдет для материалов, которые еще только будут публиковаться.
Для примера мы возьмем текстовое поле (оно будет выступать у нас в качестве поля для ввода заголовка) и напишем для него небольшой скрипт, который при вводе предложения с маленькой буквы делает его с большой:
Скрипт срабатывает как при написании текста, так и простой его вставке. Не забывайте, что для работы скриптов на вашем сайте необходимо наличие подключенной библиотеки jQuery.