String in PHP

Lecture



A string in PHP is a set of characters of any length. Unlike C, strings can also contain null characters, which does not affect the program. In other words, strings can be used to store binary data. The length of the string is limited only by the size of the freedom of RAM.

In PHP, a character is the same as a byte, which means that exactly 256 different characters are possible. This also means that PHP does not have native Unicode support. The utf8_encode () and utf8_decode () functions provide some support for Unicode.

A string can be easily processed using standard functions, you can also directly refer to any of its characters.

A simple example of a string variable:


$ a = "Это просто текст, записанный в строковую переменную" ;
echo $ a ; //Выводит 'Это просто текст, записанный в строковую переменную'
?>

And now let's take a closer look at the syntax of the string data type.

String syntax (strings)

A string can be defined in three different ways.

  • single quotes

  • double quotes

  • heredoc syntax

Single Quotes String Definition :

The simplest way to define a string is to enclose it in single quotes (the ' character).

To use a single quote within a string, as in many other languages, it must be preceded by a backslash character ( \ ), that is, it must be escaped. If the backslash must go before the single quote or at the end of the line, you need to duplicate it. Please note that if you try to escape any other character, the backslash will also be printed! So, as a rule, there is no need to escape the backslash itself.

Unlike the other two syntaxes, variables and escape sequences for special characters occur in strings enclosed in single quotes are not processed.

Here is an example of using single quotes:

echo 'это простая строка';

echo 'Также вы можете вставлять в строки
символ новой строки таким образом,
поскольку это нормально';

// Выведет: Однажды Арнольд сказал: "I'll be back"
echo 'Однажды Арнольд сказал: "I\'ll be back"';

// Выведет: Вы удалили C:\*.*?
echo 'Вы удалили C:\\*.*?';

// Выведет: Вы удалили C:\*.*?
echo 'Вы удалили C:\*.*?';

// Выведет: Это не вставит: \n новую строку
echo 'Это не вставит: \n новую строку';

// Выведет: Переменные $expand также $either не подставляются
echo 'Переменные $expand также $either не подставляются';
?>

String definition by double quotes :

If the string is enclosed in double quotes ( " ), PHP recognizes more control sequences for special characters:

Table of control sequences:

Sequence Value
\ n newline (LF or 0x0A (10) in ASCII)
\ r carriage return (CR or 0x0D (13) in ASCII)
\ t horizontal tab (HT or 0x09 (9) in ASCII)
\\ backslash
\ $ dollar sign
\ " double quote
\ [0-7] {1,3} the sequence of characters corresponding to the regular expression, the character in the octal number system
\ x [0-9A-Fa-f] {1,2} the sequence of characters that matches the regular expression, the character in hexadecimal

Recall once again that if you want to mimic any other character, the backslash will also be printed!

The most important property of strings in double quotes is variable handling. See more: string handling.

String definition by heredoc syntax :

Another way to define strings is to use the heredoc syntax (" <<< "). After <<<, you must specify an identifier, followed by a string, and then the same identifier that closes the insert.

The closing identifier must begin in the first column of the row. In addition, the identifier must comply with the same naming rules as all other labels in PHP: contain only alphanumeric characters and underscores, and must begin with a non-digit or underscore character.

Attention! It is very important to note that the line with the closing identifier does not contain other characters, with the possible exception of the semicolon ( ; ). This means that the id should not be indented and that there can be no spaces or tabs before or after the semicolon. It is also important to understand that the first character before the closing identifier must be a newline character defined in your operating system. For example, on Windows®, this is \ r .

If this rule is violated and the closing identifier is not "clean", it is assumed that there is no closing identifier and PHP will continue its search further. If in this case the correct closing identifier is not found, it will cause an error in processing with the line number at the end of the script.

Heredoc -text behaves the same as a string in double quotes, while not having them. This means that you do not need to escape quotes in heredoc, but you can still use the above control sequences. Variables are processed, but with the use of complex variables inside heredoc, you need to be as careful as when working with strings.

Example of defining a heredoc string:

$str = << Пример строки,
охватывающей несколько строчек,
с использованием heredoc-синтаксиса.
EOD;

/* Более сложный пример с переменными. */
class foo
{
var $foo;
var $bar;

function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}

$foo = new foo();
$name = 'МоеИмя';

echo << Меня зовут "$name". Я печатаю $foo->foo.
Теперь я вывожу {$foo->bar[1]}.
Это должно вывести заглавную букву 'A': \x41
EOT;
?>

Processing strings

If the string is defined in double quotes, or with the help of heredoc, the variables inside it are processed.

There are two types of syntax: simple and complex. Simple syntax is easier and more convenient. It allows the processing of a variable, an array value ( array ), or object properties ( object ).

The complex syntax was introduced in PHP 4 and can be recognized by the curly braces surrounding the expression.

Simple syntax

If the interpreter encounters a dollar sign ( $ ), it captures as many characters as possible to form the correct variable name. If you want to determine the exact end of a name, enclose the name of the variable in braces.

$beer = 'Heineken';
echo "$beer's taste is great"; // работает, "'" это неверный символ для имени переменной
echo "He drank some $beers"; // не работает, 's' это верный символ для имени переменной
echo "He drank some ${beer}s"; // работает
echo "He drank some {$beer}s"; // работает
?>

Similarly, an element of an array ( array ) or a property of an object ( object ) can be processed. In array indices, the closing square bracket ( ] ) indicates the end of the index definition. For the properties of an object, the same rules apply as for simple variables, although no trick is possible with them, as with variables.

// Эти примеры специфически об использовании массивов внутри
// строк. Вне строк всегда заключайте строковые ключи вашего
// массива в кавычки и не используйте вне строк {скобки}.

// Давайте покажем все ошибки
error_reporting(E_ALL);

$fruits = array('strawberry' => 'red', 'banana' => 'yellow');

// Работает, но заметьте, что вне кавычек строки это работает по-другому
echo "A banana is $fruits[banana].";

//Работает
echo "A banana is {$fruits['banana']}.";

// Работает, но PHP, как описано ниже, сначала ищет
// константу banana.
echo "A banana is {$fruits[banana]}.";

// Не работает, используйте фигурные скобки. Это вызовет ошибку обработки.
echo "A banana is $fruits['banana'].";

// Работает
echo "A banana is " . $fruits['banana'] . ".";

// Работает
echo "This square is $square->width meters broad.";

// Не работает. Для решения см. сложный синтаксис.
echo "This square is $square->width00 centimeters broad.";
?>

For more complex tasks, you can use complex syntax.

Difficult (figured) syntax

This syntax is called complex, not because it is difficult to understand, but because it allows the use of complex expressions.

In fact, you can include any value that is in the namespace in the string with this syntax. You simply write the expression in the same way as out-of-line, and then enclose it in {and}. Since you cannot escape '{', this syntax will only be recognized when $ immediately follows {. (Use "{\ $" or "\ {$" to display "{$"). Some illustrative examples:

// Давайте покажем все ошибки
error_reporting(E_ALL);

$great = 'fantastic';

// Не работает, выведет: This is { fantastic}
echo "This is { $great}";

// Работает, выведет: This is fantastic
echo "This is {$great}";
echo "This is ${great}";

// Работает
echo "Этот квадрат шириной {$square->width}00 сантиметров.";

// Работает
echo "Это работает: {$arr[4][3]}";

// Это неверно по той же причине, что и $foo[bar] неверно вне
// строки. Другими словами, это по-прежнему будет работать,
// но поскольку PHP сначала ищет константу foo, это вызовет
// ошибку уровня E_NOTICE (неопределенная константа).
echo "Это неправильно: {$arr[foo][3]}";

// Работает. При использовании многомерных массивов, внутри
// строк всегда используйте фигурные скобки
echo "Это работает: {$arr['foo'][3]}";

// Работает.
echo "Это работает: " . $arr['foo'][3];

echo "Вы даже можете записать {$obj->values[3]->name}";

echo "Это значение переменной по имени $name: {${$name}}";
?>

Access and change character in string :

Characters in strings can be used and modified by defining their offset from the beginning of the line, starting from zero, in curly braces after the line. Here are some examples:

// Получение первого символа строки
$str = 'Это тест.';
$first = $str{0};

// Получение третьего символа строки
$third = $str{2};

// Получение последнего символа строки
$str = 'Это все еще тест.';
$last = $str{strlen($str)-1};

// Изменение последнего символа строки
$str = 'Посмотри на море';
$str{strlen($str)-1} = 'я';

?>

String Functions and Operators

String operators

String concatenation :

Different programming languages ​​use different string concatenation operators. For example, Pascal uses the "+" operator. Using the "+" operator in PHP for concatenating strings is incorrect: if strings contain numbers, instead of concatenating strings, the operation of adding two numbers will be performed.

There are two concatenation statements in PHP.

The first is the concatenation operator ('.'), Which returns the union of the left and right argument.

The second is an assignment operator with concatenation, which appends the right argument to the left argument.

Let's give a specific example:

$a = "Hello ";
$b = $a . "World!"; // $b содержит строку "Hello World!" - Это конкатенация

$a = "Hello ";
$a .= "World!"; // $a содержит строку "Hello World!" - Это присвоение с конкатенацией
?>

String comparison operators

For comparison, strings are not recommended to use comparison operators == and! =, Since they require type conversion. Example:

php
$ x = 0 ;
$ y = 1 ;
if ($ x == "" ) echo "

x - пустая строка

" ;
if ($ y == "" ) echo "

y - пустая строка

" ;
// Выводит:
// x - пустая строка
?>

This script tells us that $ x is an empty string. This is due to the fact that the empty string ("") is interpreted primarily as 0, and only then - as "empty." In PHP, operands are compared as strings, only if both are strings. Otherwise, they are compared as numbers. In this case, any string that PHP cannot translate into a number (including an empty string) will be perceived as 0.

String comparison examples:

php
$ x = "Строка" ;
$ y = "Строка" ;
$ z = "Строчка" ;
if ($ x == $ z ) echo "

Строка X равна строке Z

" ;
if ($ x == $ y ) echo "

Строка X равна строке Y

" ;
if ($ x != $ z ) echo "

Строка X НЕ равна строке Z

" ;
// Выводит:
// Строка X равна строке Y
// Строка X НЕ равна строке Z
?>

To avoid confusion and type conversion, it is recommended to use the equivalence operator when comparing strings. The equivalence operator allows one to always correctly compare strings, since it compares values ​​both by value and type:

php
$ x = "Строка" ;
$ y = "Строка" ;
$ z = "Строчка" ;
if ($ x == = $ z ) echo "

Строка X равна строке Z

" ;
if ($ x === $ y ) echo "

Строка X равна строке Y

" ;
if ($ x !== $ z ) echo "

Строка X НЕ равна строке Z

" ;
// Выводит:
// Строка X равна строке Y
// Строка X НЕ равна строке Z
?>

Functions for working with strings

There are many useful functions for working with strings in PHP.

Let's briefly analyze some of the functions for working with strings.

Basic string functions

strlen (string $ st)

One of the most useful features. Returns just the length of the string, i.e., how many characters are contained in $ st . The string can contain any characters, including those with a zero code (which is forbidden in C). Example:

$x = "Hello!";
echo strlen($x); // Выводит 6

strpos (string $ where, string $ what, int $ from where = 0)

It tries to find a substring in the $ where string (that is, a sequence of characters) $ what and, if successful, returns the position (index) of this substring in the string. The optional $ fromwhere parameter can be specified if the search needs to be conducted not from the beginning of the $ from line , but from some other position. In this case, this position should be passed to $ fromwhere . If the substring could not be found, the function returns false . However, be careful when checking the result of the strpos () call to false - use only the === operator for this. Example:

echo strpos("Hello","el"); // Выводит 1

And another example:

if (strpos("Norway","rwa") !== false) echo "Строка rwa есть в Norway";
// При сравнении используйте операторы тождественных сравнений (===) (!==) чтобы избежать проблем с определением типов

substr (string $ str, int $ start [, int $ length])

This function is also claimed very often. Its purpose is to return a section of the $ str line , starting at the $ start position and $ length long. If $ length is not specified, then a substring from $ start to the end of $ str is implied. If $ start is greater than the length of the string, or $ length is zero, then an empty substring is returned. However, this feature can do quite useful things. For example, if we pass a negative number to $ start , it will be assumed that this number is a substring index, but only counted from the end of $ str (for example, -1 means "starting from the last character of the string"). The $ length parameter, if specified, can also be negative. In this case, the last character of the returned substring will be the character from $ str with the index $ length determined from the end of the string. Examples:

$str = "Programmer";
echo substr($str,0,2); // Выводит Pr
echo substr($str,-3,3); // Выводит mer

strcmp (string $ str1, string $ str2)

Compares two strings character-by-character (more precisely, byte-by-byte) and returns: 0 , if the strings completely match; -1 if $ str1 is lexicographically less than $ str2 ; and 1 , if, on the contrary, $ str1 is "larger" $ str2 . Since the comparison is byte-byte, the case of characters affects the results of comparisons.

strcasecmp (string $ str1, string $ str2)

The same as strcmp (), only when working is not case sensitive. For example, from the point of view of this function, "ab" and "AB" are equal.

Functions for working with text blocks

The functions listed below are most often useful if you need to perform single-type operations with multi-line blocks of text specified in string variables.

str_replace (string $ from, string $ to, string $ str)

Replaces all occurrences of the $ from substring (case sensitive) with $ to in the $ str string and returns the result. The source string passed by the third parameter does not change. This function works much faster than ereg_replace () , which is used when working with regular PHP expressions, and it is often used if there is no need for some exotic substring search rules. For example, this is how we can replace all newline characters with their HTML equivalent - the
tag:

$st=str_replace("\n","
\n",$str)

As you can see, the fact that the string
\ n is also a newline character does not affect the operation of the function in any way, that is, the function performs only a single pass through the string. To solve this problem, the nl2br () function is also applicable, which works a little faster.

string nl2br (string $ string)

Replaces all newline characters in a string \ n with
\ n and returns the result. The original string is unchanged. Please note that the \ r characters that appear at the end of a line of Windows text files are not taken into account by this function, and therefore remain in the old place.

WordWrap (string $ str, int $ width = 75, string $ break = "\ n")

This function, which appeared in PHP4 , turns out to be incredibly useful, for example, when formatting the text of a letter before automatically sending it to the addressee using mail () . It splits the text block of $ str into several lines, terminated by $ break characters, so that no more than $ width of letters is on one line. The splitting takes place along a word boundary, so the text remains readable. Returns the resulting string with newline characters specified in $ break . Example of use:

php
$ str = "Это текст электронного письма, которое нужно будет отправить адресату..." ;
// Разбиваем текст по 20 символов
$ str = WordWrap ($ str , 20 , "
"
);
echo $ str ;
// Выводит:
/* Это текст
электронного письма,
которое нужно будет
отправить
адресату... */
?>

strip_tags (string $ str [, string $ allowable_tags])

Another useful feature for working with strings. This function removes all tags from the string and returns the result. In the $ allowable_tags parameter, you can pass tags that should not be removed from the string. They should be listed close to each other. Examples:

$stripped = strip_tags ($str); // Удаляет все html - теги из строки (текста)
$stripped = strip_tags($str, "

"); // Удалит все html - теги, кроме html - тегови

Functions for working with individual characters

As in other programming languages, in PHP you can work with string characters separately.

You can refer to any character of a string by its index:

$str = "PHP";
echo $str[0]; // Выводит 'P'

chr (int $ code)

This function returns a string consisting of a character with the code $ code . Example:

echo chr(75); //Выводит K

ord ($ char)

This function returns the character code $ char . Here is an example:

echo ord('A'); // Выводит 65 - код буквы 'A'

Space removal functions

It is sometimes difficult to even imagine what strange users might be if you give them a keyboard and ask them to type a word on it. Since the spacebar is the largest, users tend to press it at the most incredible moments. This is also facilitated by the fact that the symbol with code 32, indicating a space, as you know, is not visible on the screen. If the program is not able to handle the situation described, then, at best, after a silent silence, it will display something like "incorrect input data" in the browser, and at worst, it will do something irreversible.

Meanwhile, it is extremely easy to protect yourself from parasitic spaces, and PHP developers provide us with a number of specialized functions. Do not worry that their use slows down the program. These functions operate at lightning speed, and most importantly, equally quickly, regardless of the size of the lines passed to them.

trim (string $ str)

Returns a copy of $ str, only with leading and trailing whitespace characters removed. By white space, I hereinafter imply: space "", line feed character \ n, carriage return character \ r and tab character \ t. For example, calling trim ("test \ n") returns the string "test". This feature is used very widely. Try to apply it wherever there is even the slightest suspicion of the presence of erroneous spaces. Since it works very quickly.

ltrim (string $ st)

Same as trim () , only removes only leading spaces, and does not touch the trailing ones. Used much less frequently.

chop (string $ st)

Removes only trailing spaces, leading does not touch.

Character conversion functions

Web programming is one of those areas in which you constantly have to manipulate strings: break them, add and remove spaces, transcode into different encodings, and finally URL encode and decode. In PHP, it is impossible to implement all these actions manually using only the primitives already described, for reasons of speed. Therefore, there are similar built-in functions.

strtr (string $ str, string $ from, string $ to)

This function is not widely used, but sometimes it is still quite useful. It replaces in the $ str line all the characters found in $ from with their "pairs" (that is, located in the same positions as in $ from ) from $ to .

The following several features are provided for fast URL encoding and decoding.

URL coding is required for data transmission over the Internet. For example, such encoding is advisable if you pass Russian-language information as a script parameter. Also, such encoding can be performed for the file, so that no collisions occur due to the lack of support for 8-bit encodings by some servers. These functions are:

UrlEncode (string $ str)

The function URL encodes the string $ str and returns the result. This function is useful if, for example, you want to dynamically form a link to some scenario, but you are not sure that its parameters contain only alphanumeric characters. In this case, use the function like this:

echo "

Now, even if the $ UserData variable includes the characters = , &, or even spaces anyway, the correct data will be passed to the script.

UrlDecode (string $ st)

Produces URL decode string. In principle, it is used much less frequently than UrlEncode () , because PHP can already transcode the input data automatically.

RawUrlEncode (string $ st)

Almost completely similar to UrlEncode () , but only spaces are not converted to + , as is done when transferring data from a form, but are perceived as ordinary non-alphanumeric characters. However, this method does not generate any additional incompatibilities in the code.

RawUrlDecode (string $ st)

It is similar to UrlDecode () , but does not perceive + as a space.

HtmlSpecialChars (string $ str)

This is a function that is commonly used in combination with echo . Its main purpose is to ensure that no section in the output line will be perceived as a tag.

Replaces some characters in the string (such as ampersant, quotation marks and "more" and "less" signs) with their HTML equivalents, so that they look like "themselves" on the page. The most typical application of this function is the formation of the value parameter in various form elements so that there are no problems with quotes, or the output of a message in the guest book if the user is not allowed to insert tags.

StripSlashes (string $ str)

Replaces some preceded slashes with single-code equivalents in the $ str string. This refers to the following characters: " , ' , \ and no other.

AddSlashes (string $ str)

Inserts slashes only before the following characters: ', "and \. The function is very convenient to use when calling eval () (this function executes the string passed to it in parameters, as if it deals with a small PHP program.

Register Change Functions

Quite often we have to translate some lines, say, in upper case, that is, to make all capital letters in a line capitalized. In principle, for this purpose we could use the function strtr () , discussed above, but it will still not work as fast as we sometimes would like. In PHP, there are functions that are specifically designed for such needs. Here they are:

strtolower (string $ str)

Converts a string to lowercase. Returns the result of the transfer.

It should be noted that if the locale is set incorrectly (this is a set of rules for translating characters from one register to another, translating date and time, currency units, etc.), the function will produce incorrect results when working with Cyrillic letters.
Perhaps, in simple programs, and also if there is no confidence in the support of the corresponding locale by the operating system, it will be easier to use the "manual" character conversion, using the strtr () function:

$st=strtr($st, "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩљЫЬЭЮЯ", "абвгдеёжзийклмнопрстуфхцчшщъыьэюя");

Главное достоинство данного способа — то, что в случае проблем с кодировкой для восстановления работоспособности сценария вам придется всего лишь преобразовать его в ту же кодировку, в которой у вас хранятся документы на сервере.

strtoupper(string $str)

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

Установка локали (локальных настроек)

Локалью будем называть совокупность локальных настроек системы, таких как формат даты и времени, язык, кодировка.

Настройки локали сильно зависят от операционной системы.

Для установки локали используется функция SetLocale() :

SetLocale(string $category, string $locale)

The function sets the current locale with which the functions of case-conversion, date-time output, etc. will work. Generally speaking, for each category of functions, the locale is defined separately and looks different. Which category of functions will be affected by the call to SetLocale () is specified in the $ category parameter . It can take the following string values:

LC_CTYPE — активизирует указанную локаль для функций перевода в верх-
ний/нижний регистры;
LC_NUMERIC — активизирует локаль для функций форматирования дробных чи-
сел — а именно, задает разделитель целой и дробной части в числах;
LC_TIME — задает формат вывода даты и времени по умолчанию;
LC_ALL — устанавливает все вышеперечисленные режимы.

Теперь о параметре $locale . Как известно, каждая локаль, установленная в системе, имеет свое уникальное имя, по которому к ней можно обратиться. Именно оно и фиксируется в этом параметре. Однако, есть два важных исключения из этого правила. Во-первых, если величина $locale равна пустой строке "", то устанавливается та локаль, которая указана в глобальной переменной окружения с именем, совпадающим с именем категории $category (или LANG — она практически всегда присутствует в Unix). Во вторых, если в этом параметре передается 0, то новая локаль не устанавливается, а просто возвращается имя текущей локали для указанного режима.

К сожалению, имена локалей задаются при настройке операционной системы, и для них, по-видимому, не существует стандартов. Выясните у своего хостинг-провайдера, как называются локали для разных кодировок русских символов. Но, если следующий фрагмент работает у вашего хостинг-провайдера, это не означает, что он заработает, например, под Windows:

setlocale('LC_CTYPE','ru_SU.KOI8-R');

Здесь вызов устанавливает таблицу замены регистра букв в соответствии с кодировкой KOI8-R.

По правде говоря, локаль - вещь довольно непредсказуемая и довольно плохо переносимая между операционными системами. Так что, если ваш сценарий не очень велик, задумайтесь: возможно, лучше будет искать обходной путь, например, используя strtr() , а не рассчитывать на локаль.

Функции преобразования кодировок

Часто встречается ситуация, когда нам требуется преобразовать строку из одной кодировки кириллицы в другую. Например, мы в программе сменили локаль: была кодировка windows , а стала — KOI8-R . Но строки-то остались по-прежнему в кодировке WIN-1251 , а значит, для правильной работы с ними нам нужно их перекодировать в KOI8-R. Для этого и служит функция преобразования кодировок.

convert_cyr_string(string $str, char $from, char $to);

Функция переводит строку $str из кодировки $from в кодировку $to. Конечно, это имеет смысл только для строк, содержащих "русские" буквы, т. к. латиница во всех кодировках выглядит одинаково. Разумеется, кодировка $from должна совпадать с истинной кодировкой строки, иначе результат получится неверным. Значения $from и $to — один символ, определяющий кодировку:

k — koi8-r
w — windows-1251
i — iso8859-5
a — x-cp866
d — x-cp866
m — x-mac-cyrillic

Функция работает достаточно быстро, так что ее вполне можно применять, скажем, для перекодировки писем в нужную форму перед их отправкой по электронной почте.

Функции форматных преобразований строк

Как мы знаем, переменные в строках PHP интерполируются, поэтому практически всегда задача "смешивания" текста со значениями переменных не является проблемой. Например, мы можем спокойно написать что-то вроде:

echo "Привет, $name! Вам $age лет.";

В Си для аналогичных целей используется следующий код:

printf("Привет, %s! Вам %s лет",name,age);

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

sprintf(string $format [, mixed args, ...])

Эта функция — аналог функции sprintf() в Си. Она возвращает строку, составленную на основе строки форматирования, содержащей некоторые специальные символы, которые будут впоследствии заменены на значения соответствующих переменных из списка аргументов.
Строка форматирования $format может включать в себя команды форматирования, предваренные символом % . Все остальные символы копируются в выходную строку как есть. Каждый спецификатор формата (то есть, символ % и следующие за ним команды) соответствует одному, и только одному параметру, указанному после параметра $format . Если же нужно поместить в текст % как обычный символ, необходимо его удвоить:

echo sprintf("The percentage was %d%%",$percentage);

Каждый спецификатор формата включает максимум пять элементов (в порядке их следования после символа %):

>>> Необязательный спецификатор размера поля, который указывает, сколько символов будет отведено под выводимую величину. В качестве символов-заполнителей (если значение имеет меньший размер, чем размер поля для его вывода) может использоваться пробел или 0, по умолчанию подставляется пробел. Можно задать любой другой символ-наполнитель, если указать его в строке форматирования, предварив апострофом '.

>>> Опциональный спецификатор выравнивания, определяющий, будет результат выровнен по правому или по левому краю поля. По умолчанию производится выравнивание по правому краю, однако можно указать и левое выравнивание, задав символ - (минус).

>>> Необязательное число, определяющее размер поля для вывода величины. Если результат не будет в поле помещаться, то он "вылезет" за края этого поля, но не будет усечен.

>>> Необязательное число, предваренное точкой ".", предписывающее, сколько знаков после запятой будет в результирующей строке. Этот спецификатор учитывается только в том случае, если происходит вывод числа с плавающей точкой, в противном случае он игнорируется.

>>> Наконец, обязательный (заметьте — единственный обязательный!) спецификатор типа величины, которая будет помещена в выходную строку:

b — очередной аргумент из списка выводится как двоичное целое число;
c — выводится символ с указанным в аргументе кодом;
d — целое число;
f — число с плавающей точкой;
o — восьмеричное целое число;
s — строка символов;
x — шестнадцатеричное целое число с маленькими буквами az ;
X — шестнадцатеричное число с большими буквами A—Z .

Вот как можно указать точность представления чисел с плавающей точкой:

$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money выведет "123.1"...
$formatted = sprintf ("%01.2f", $money);
// echo $formatted выведет "123.10"
!

Вот пример вывода целого числа, предваренного нужным количеством нулей:

$isodate=sprintf("%04d-%02d-%02d",$year,$month,$day);

printf(string $format [, mixed args, ...])

Делает то же самое, что и sprintf() , только результирующая строка не возвращается, а направляется в браузер пользователя.

number_format(float $number, int $decimals, string $dec_point=".", string $thousands_sep=",");

Эта функция форматирует число с плавающей точкой с разделением его на триады с указанной точностью. Она может быть вызвана с двумя или четырьмя аргументами, но не с тремя! Параметр $decimals задает, сколько цифр после запятой должно быть у числа в выходной строке. Параметр $dec_point представляет собой разделитель целой и дробной частей, а параметр $thousands_sep — разделитель триад в числе (если указать на его месте пустую строку, то триады не отделяются друг от друга).

В PHP существует еще несколько функций для выполнения форматных преобразований, среди них - sscanf() и fscanf() , которые часто применяются в Си . Однако в PHP их использование весьма ограничено: чаще всего для разбора строк оказывается гораздо выгоднее привлечь регулярные выражения или функцию explode() .

Hash functions

md5(string $str)

Возвращает хэш-код строки $str , основанный на алгоритме корпорации RSA Data Security под названием " MD5 Message-Digest Algorithm ". Хэш-код — это просто строка, практически уникальная для каждой из строк $str . То есть вероятность того, что две разные строки, переданные в $str , дадут нам одинаковый хэш-код, стремится к нулю.

Если длина строки $str может достигать нескольких тысяч символов, то ее MD5-код занимает максимум 32 символа.

Для чего нужен хэш-код и, в частности, алгоритм MD5 ? Например, для проверки паролей на истинность.

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

Сделаем так: в файле паролей будем хранить не сами пароли, а их ( MD5 ) хэш-коды. При попытке какого либо пользователя войти в систему мы вычислим хэш-код только что введенного им пароля и сравним его с тем, который записан у нас в базе данных. Если коды совпадут, значит, все в порядке, а если нет — что ж, извините...
Конечно, при вычислении хэш-кода какая-то часть информации о строке $str безвозвратно теряется. И именно это позволяет нам не опасаться, что злоумышленник, получивший файл паролей, сможет его когда-нибудь расшифровать. Ведь в нем нет самих паролей, нет даже их каких-то связных частей!

Пример использования алгоритма хеширования MD5:

php
$ pass_a = "MySecret" ;
$ pass_b = "MySecret" ;
// Выводим хеш-код строки MySecret ($pass_a) - исходный пароль
echo "Хеш-код исходного пароля '$pass_a':" . md5 ($ pass_a ). "
"
;
// Выводим хеш-код строки MySecret ($pass_b) - верифицируемый пароль
echo "Хеш-код верифицируемого пароля '$pass_b':" . md5 ($ pass_b ). "
" ;
// Сравниваем хеш-коды MD5 исходного и верифицируемого пароля
echo "

Проверяем истинность введенного пароля:

" ;
if ( md5 ($ pass_a )=== md5 ($ pass_b )) echo "

Пароль верный! (Хеш-коды совпадают)

" ;
else echo "

Пароль неверный! (Хеш-коды не совпадают)

"
// В данной ситуации выводит: Пароль верный! (Хеш-коды совпадают)
// Попробуйте изменить значение строки $pass_b :)
?>

crc32(string $str)

Функция crc32() вычисляет 32-битную контрольную сумму строки $str. То есть, результат ее работы — 32 битное (4-байтовое) целое число. Эта функция работает гораздо быстрее md5(), но в то же время выдает гораздо менее надежные "хэш-коды" для строки.

Функции сброса буфера вывода

flush()

Эта функция имеет очень и очень отдаленное отношение к работе со строками, но она еще дальше отстоит от других функций.

Начнем издалека: обычно при использовании echo данные не прямо сразу отправляются клиенту, а накапливаются в специальном буфере, чтобы потом транспортироваться большой "пачкой". Так получается быстрее.

Однако, иногда бывает нужно досрочно отправить все данные из буфера пользователю, например, если вы что-то выводите в реальном времени (так зачастую работают чаты). Вот тут-то вам и поможет функция flush() , которая отправляет содержимое буфера echo в браузер пользователя.

Если вы все еще не нашли, что искали, смотрите функции для символьного типа.

Преобразование в строковый тип

Вы можете преобразовывать значения в строковый тип, используя приведение (string) , либо функцию strval() .

В выражениях, где необходима строка, преобразование происходит автоматически. Это происходит, когда вы используете функции echo() или print() , либо когда вы сравниваете значение переменной со строкой. Смотрите также: Манипуляции с типами данных и settype() .

Булевое ( boolean ) значение TRUE преобразуется в строку "1" , а значение FALSE представляется как "" (пустая строка). Этим способом вы можете преобразовывать значения в обе стороны - из булева типа в строковый и наоборот.

Целое ( integer ) или число с плавающей точкой ( float ) преобразуется в строку, представленную числом, состоящим из его цифр (включая показатель степени для чисел с плавающей точкой).

Массивы всегда преобразуются в строку "Array" , так что вы не можете отобразить содержимое массива ( array ), используя echo() или print() , чтобы узнать, что он содержит. Чтобы просмотреть один элемент, вам нужно сделать что-то вроде echo $arr['foo'] .

Объекты всегда преобразуются в строку "Object" . Если вы хотите вывести значение переменной-члена объекта ( object ) с целью отладки, прочтите следующие абзацы. Если вы хотите получить имя класса требуемого объекта, используйте get_class() .

Ресурсы всегда преобразуются в строки со структурой "Resource id #1" , где 1 - это уникальный номер ресурса ( resource ), присвоенный ему PHP во время выполнения. Если вы хотите получить тип ресурса, используйте get_resource_type() .

NULL всегда преобразуется в пустую строку.

Вывод массивов, объектов или ресурсов не предоставляет вам никакой полезной информации о самих значениях. Более подходящий способ вывода значений для отладки - использовать функции print_r() и var_dump() .

Вы также можете преобразовывать значения PHP в строки для постоянного хранения. Этот метод называется сериализацией и может быть выполнен при помощи функции serialize() . Кроме того, если в вашей установке PHP есть поддержка WDDX , вы можете сериализовать значения PHP в структуры XML.

Преобразование строк в числа

Если строка распознается как числовое значение, результирующее значение и тип определяется так как показано далее.

Строка будет распознана как float , если она содержит любой из символов '.', 'e', или 'E'. Иначе она будет определена как целое.

Значение определяется по начальной части строки. Если строка начинается с верного числового значения, будет использовано это значение. Иначе значением будет 0 (ноль). Верное числовое значение - это одна или более цифр (могущих содержать десятичную точку), по желанию предваренных знаком, с последующим необязательным показателем степени. Показатель степени - это 'e' или 'E' с последующими одной или более цифрами.

$foo = 1 + "10.5"; // $foo это float (11.5)
$foo = 1 + "-1.3e3"; // $foo это float (-1299)
$foo = 1 + "bob-1.3e3"; // $foo это integer (1)
$foo = 1 + "bob3"; // $foo это integer (1)
$foo = 1 + "10 Small Pigs"; // $foo это integer (11)
$foo = 4 + "10.2 Little Piggies"; // $foo это float (14.2)
$foo = "10.0 pigs " + 1; // $foo это float (11)
$foo = "10.0 pigs " + 1.0; // $foo это float (11)
?>

Более подробную информацию об этом преобразовании смотрите в разделе о strtod(3) документации Unix .

If you want to test any of the examples in this section, you can copy and paste it and the following line to see what happens:

echo "\$foo==$foo; тип: " . gettype ($foo) . "
\n";
?>

Do not expect to receive a character code by converting it to an integer (as you would do, for example, in C). To convert characters to their codes and back, use the functions ord () and chr () .

created: 2016-01-25
updated: 2023-06-03
132707



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)