php first letter uppercase

Как сделать первую букву заглавной php кирилица

Достаточно редко, но всё-же возникает такая необходимость, как сделать первую букву заглавной php кирилица.

Это когда первая буква слова становится большой. Применить это можно, например, для унификации написания имени пользователя, или, например, когда нужно автоматически составить текст в предложение.

Как сделать первую букву заглавной php латиница

Тут всё достаточно просто: в PHP есть 2 функции: ucfirst() и ucwords(). Первая делает только первую букву в строке заглавной, вторая делает первую букву каждого слова в строке заглавной.

В результате получим две строки:
First letters
и
First Letters

Видим разницу. С английскими текстами (или любыми другими), написанными латиницей проблем не будет.

Как сделать первую букву заглавной php кирилица Windows-1251 (CP-1251)

С кирилицей (русскими буквами) которые записаны в кодировки Windows-1251 тоже не будет больших проблем:

В результате получим две строки:
Первые буквы
и
Первые Буквы

Как сделать первую букву заглавной php кирилица UTF-8

Но как только дело доходит до UTF-8 начинаются проблемы, потому, что кирилица в UTF-8 занимает 2 байта, и поэтому ничего не получится. Для этого будем использовать «костыль» от Multibyte String Functions. Если этот плагин установлен на PHP, то можно просто использовать 2 аналогичные функции: mb_ucfirst и mb_convert_case.

А если их нет, то нужно дополнить код своими альтернативами:

Результатом этому коду станут такие строчки:

первые буквы
первые буквы
Первые буквы
Первые Буквы

Как видите, первые 2 строчки не сработали, из-за того, что обычные ucfirst и ucwords не умеют работать с кирилицей в UTF-8.

С помощью этих функций можно построить успешный бизнес на продвижении сайтов. Ну не только на этих функциях, но поверьте, в продвижении сайтов всегда нужно всё максимально автоматизировать.

Источник

ucfirst

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

ucfirst — Make a string’s first character uppercase

Description

Returns a string with the first character of string capitalized, if that character is alphabetic.

Note that ‘alphabetic’ is determined by the current locale. For instance, in the default «C» locale characters such as umlaut-a (ä) will not be converted.

Parameters

Return Values

Returns the resulting string.

Examples

Example #1 ucfirst() example

See Also

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.

Источник

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

Источник

Uppercase first letter and rest lower

Ive been looking around for a way in PHP to have a string converted, so that the first letter becomes uppercase and the rest lower case.

At the moment I am doing what I believe is the standard way:

But I have found that some programming languages (ie. tcl) can do it with one cammand:

Is there a way to do this in PHP? It’s not a problem as such, I’m just a curios dude 😀

6 Answers 6

php first letter uppercase. Смотреть фото php first letter uppercase. Смотреть картинку php first letter uppercase. Картинка про php first letter uppercase. Фото php first letter uppercase

«Title» casing capitalizes each word in a string (i.e. every letter following white space). Your approach would result in «Gone with the wind,» whereas title casing would yield «Gone With The Wind».

I wouldn’t worry about it: what you’re doing is simple and intuitive, and if it gets you what you want, there’s not any intrinsic functions that do the same thing.

php first letter uppercase. Смотреть фото php first letter uppercase. Смотреть картинку php first letter uppercase. Картинка про php first letter uppercase. Фото php first letter uppercase

You can create such function yourself.

Do not forget that you should use mb_* functions for data that was input by user. English is not the only language people use. Look at this question: ucfirst() function for multibyte character encodings

You should go like this

There is a single, native function that performs title-casing and is multibyte-safe. This is a very tidy solution because you don’t need to prepare the string to be all lowercase before making the leading letter of all words uppercase.

The above demonstrates that the coment at https://www.php.net/manual/en/function.mb-convert-case.php#119629 is incorrect about the behavior relating to double-quote wtapped words.

Источник

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! “

Источник

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

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