Рядок (string) — це набір символів, кожному з яких відповідає певний байт. Це означає, що PHP підтримує всього 256 різних символів, а отже не має вбудованої підтримки Unicode. Див. деталі про рядковий тип.
Зауваження: В 32-бітних збірках значення типу string може мати розмір до 2ГБ (2147483647 байт).
Записувати символами значення типу string можна чотирма способами:
Найпростіший спосіб означити рядок (string) — взяти його в
апострофи (наприклад 'це рядкове значення'
).
Щоб вписати в рядок апостроф, цей знак необхідно екранувати
оберненою косою рискою (\
). Щоб всередині рядкового
значення вписати обернену косу риску, треба продублювати її
(\\
). Всі наступні символи оберненої косої риски будуть
сприйматись буквально: це означає, що всі інші екрановані послідовності,
наприклад \r
або \n
будуть виводитись
буквально, а не як такі, що мають спеціальне значення.
Зауваження: На відміну від лапок та синтаксису heredoc, змінні та екрановані послідовності спеціальних символів не будуть розкриті в рядках, взятих в апострофи.
<?php
echo 'це звичайний рядок';
echo 'Також можна додавати
символ нового рядка,
це допустимо';
// Виводить: Якось Арнольд сказав: "I'll be back"
echo 'Якось Арнольд сказав: "I\'ll be back"';
// Виводить: Ви видалили C:\*.*?
echo 'Ви видалили C:\\*.*?';
// Виводить: Ви видалили C:\*.*?
echo 'Ви видалили C:\*.*?';
// Виводить: Це не розкриється: \n a newline
echo 'Це не розкриється: \n a newline';
// Виводить: Змінні $також $не_розкриваються
echo 'Змінні $також $не_розкриваються';
?>
Якщо рядок (string) взято в лапки ("
), то
PHP інтерпретує наступні екрановані послідовності у спеціальні символи:
Послідовність | Значення |
---|---|
\n |
новий рядок (LF (linefeed) або 0x0A (10) в ASCII) |
\r |
повернення каретки (CR (carriage return) або 0x0D (13) в ASCII) |
\t |
горизонтальна табуляція (HT (horizontal tab) або 0x09 (9) в ASCII) |
\v |
вертикальна табуляція (VT (vertical tab) або 0x0B (11) в ASCII) |
\e |
escape-символ (ESC або 0x1B (27) в ASCII) |
\f |
розрив сторінки (FF (form feed) або 0x0C (12) в ASCII) |
\\ |
обернена коса риска |
\$ |
знак долара |
\" |
лапка |
\[0-7]{1,3} |
Вісімкове число: послідовність символів, що відповідає регулярному
виразу [0-7]{1,3} та є вісімковою формою запису
символа (напр. "\101" === "A" ), що неявно
переповнюється, щоб відповідати одному байту (напр.
"\400" === "\000" )
|
\x[0-9A-Fa-f]{1,2} |
Шістнадцяткове число: послідовність символів, що відповідає регулярному
виразу [0-9A-Fa-f]{1,2} та є шістнадцятковою формою
запису символа (напр. "\x41" === "A" )
|
\u{[0-9A-Fa-f]+} |
Unicode: послідовність символів, що відповідає регулярному виразу
[0-9A-Fa-f]+ та є кодовою точкою UTF-8, символ якої
буде вставлено у рядок. Фігурні дужки є обов'язковими у цій
послідовності. Наприклад "\u{41}" === "A"
|
В рядках (string), що взяті в апострофи, екранування інших символів також призведе до друку оберненої косої риски.
Найважливішою особливістю рядків (string) в лапках є розкривання значень змінних. Детальніше: Інтерполяція рядків.
Третій спосіб запису значення типу string — синтаксис heredoc:
<<<
. Після цього оператора слідують
мітка та символ нового рядка. Далі — власне, текст (string), а
потім та сама мітка з нового рядка. Вона позначає кінець тексту.
В кінці перед міткою можуть бути пропуски або символи табуляції. Тоді такі ж відступи будуть видалені з початку усіх рядків тексту. До PHP 7.3.0, мітка в кінці повинна бути одразу після символа нового рядка.
Також мітка має відповідати правилам називання міткок в PHP: містити тільки букви, цифри, підкреслення та починатися з букви або підкреслення.
Приклад #1 Простий приклад Heredoc, починаючи з PHP 7.3.0
<?php
// без відступів
echo <<<МІТКА
а
б
в
\n
МІТКА;
// відступ з 4-х пропусків
echo <<<МІТКА
а
б
в
МІТКА;
В PHP 7.3 поданий вище приклад виведе:
а б в а б в
Якщо кінцева мітка відступає далі ніж будь-який рядок тексту, то викинеться ParseError:
Приклад #2 Кінцева мітка не має відступати далі ніж будь-який рядок тексту
<?php
echo <<<МІТКА
а
б
в
МІТКА;
В PHP 7.3 поданий вище приклад виведе:
PHP Parse error: Invalid body indentation level (expecting an indentation level of at least 3) in example.php on line 4
Для відступу кінцевої мітки можна використовувати табуляцію, однак табуляція та пропуски не повинні змішуватися у відступах тексту чи кінцевої мітки. Інакше, буде викинуто ParseError. Це обмеження було введено у зв'язку з тим, що змішування табуляції та пропусків погіршує розбірливість коду.
Приклад #3 Різні відступи
<?php
// Увесь наступний код не працює.
// різні відступи в тексті (пропуски) та для кінцевої мітки (табуляція)
{
echo <<<МІТКА
а
МІТКА;
}
// змішування пропусків та табуляції в тексті
{
echo <<<МІТКА
а
МІТКА;
}
// змішування пропусків та табуляції для кінцевої мітки
{
echo <<<МІТКА
а
МІТКА;
}
В PHP 7.3 поданий вище приклад виведе:
PHP Parse error: Invalid indentation - tabs and spaces cannot be mixed in example.php line 8
Крапка з комою чи символ нового рядка після кінцевої мітки не є обов'язковими. До прикладу, наступний код дозволений, починаючи з PHP 7.3.0:
Приклад #4 Продовження виразу після кінцевої мітки
<?php
$значення = [<<<МІТКА
а
б
в
МІТКА, 'г ґ д'];
var_dump($значення);
В PHP 7.3 поданий вище приклад виведе:
array(2) { [0]=> string(14) "а б в" [1]=> string(8) "г ґ д" }
Якщо назву мітки знайдено одразу після символу початку рядка, то навіть якщо це була частина тексту, вона розглядатиметься як кінцева мітка, що спричинить помилку ParseError.
Приклад #5 Кінцева мітка в тексті може викликати ParseError
<?php
$значення = [<<<МІТКА
а
б
МІТКА помічає кінець тексту
МІТКА, 'в г ґ'];
В PHP 7.3 поданий вище приклад виведе:
PHP Parse error: syntax error, unexpected identifier "помічає", expecting "]" in example.php on line 5
Щоб уникнути цієї проблеми, безпечніше дотримуватися простого правила: не обирати мітку, яка може з'явитися в тексті.
До PHP 7.3.0, необхідно слідкувати за тим, щоб рядок з кінцевою міткою не
містив нічого, крім самої мітки та крапки з комою (;
) за
нею. Це означає, що мітка не може відступати від
початку рядка, а також не може бути жодних пропусків чи табуляції перед чи
після крапки з комою. Також важливо, щоб символом перед кінцевою міткою
був символ нового рядка, визначений локальною операційною системою. Це
\n
в системах UNIX, включно з macOS. Також цей символ
має бути одразу після крапки з комою.
Якщо це правило порушено і кінцева мітка неправильна — вона не вважатиметься такою, а PHP продовжить шукати кінцеву мітку. Якщо до кінця поточного файлу мітку не буде знайдено, то на останньому рядку виникне синтаксична помилка.
Приклад #6 Недійсна мітка, до версії PHP 7.3.0
<?php
class foo {
public $bar = <<<МІТКА
bar
МІТКА;
}
// Мітка повинна не мати відступів
?>
Приклад #7 Дійсна мітка, навіть до версії PHP 7.3.0
<?php
class foo {
public $bar = <<<МІТКА
bar
МІТКА;
}
?>
Дані рядкового типу в синтаксисі Heredoc, які містять змінні, не можна використовувати для ініціалізації властивостей класу.
Текст Heredoc має ті ж особливості, що і рядок (string) в лапках, просто без лапок. Це означає, що лапки в Heredoc не потрібно екранувати, а перелічені вище екрановані послідовності досі можна використовувати. Змінні так само розкриваються, а складні змінні записуються тим же способом, що і в рядках (string).
Приклад #8 Вставлення інших рядків в Heredoc
<?php
$str = <<<EOD
Приклад тексту
з синтаксисом heredoc,
що складається з кількох рядків.
EOD;
/* Складніший приклад, зі змінними. */
class foo
{
var $foo;
var $bar;
function __construct()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'Петро';
echo <<<EOT
Мене звати $name. Я друкую $foo->foo.
Зараз я друкую {$foo->bar[1]}.
Має надрукуватись велика буква 'A': \x41
EOT;
?>
Поданий вище приклад виведе:
Мене звати Петро. Я друкую Foo. Зараз я друкую Bar2. Має надрукуватись велика буква 'A': A
Також можливо використовувати Heredoc-синтаксис для передавання параметрів до функції:
Приклад #9 Heredoc в значеннях параметрів
<?php
var_dump(array(<<<EOD
foobar!
EOD
));
?>
Можна задавати значення статичним змінним та властивостям/константам класу, використовуючи синтаксис Heredoc:
Приклад #10 Heredoc як статичне значення
<?php
// Поле класу
function foo()
{
static $bar = <<<LABEL
Тут нічого цікавого...
LABEL;
}
// Властивість, константа класу
class foo
{
const BAR = <<<FOOBAR
Приклад константи
FOOBAR;
public $baz = <<<FOOBAR
Приклад властивості
FOOBAR;
}
?>
Початкову мітку Heredoc можна брати в лапки:
Приклад #11 Використання лапок в Heredoc
<?php
echo <<<"FOOBAR"
Привіт, світ!
FOOBAR;
?>
Синтаксис nowdoc стосується рядків в апострофах, як heredoc — рядків в
лапках, тобто працює схожим способом до heredoc, але без
інтерполяції тексту всередині. Така конструкція прекрасно
підходить для вставлення PHP-коду або великих частин тексту без необхідності
їхнього екранування. Цей синтаксис має деякі спільні риси з конструкцією
SGML <![CDATA[ ]]>
, оскільки він оголошує блок
тексту, який не підлягає аналізу.
Nowdoc починається з тої ж послідовності <<<
, що
й heredocs, але назва мітки, що йде далі, береться в апострофи, напр.
<<<'EOT'
. Усі правила щодо міток heredoc
застосовуються також до міток nowdoc, особливо ті, що стосуються кінцевої
мітки.
Приклад #12 Приклад тексту nowdoc
<?php
echo <<<'МІТКА'
Приклад тексту з кількома рядками
з використанням синтаксису nowdoc.
Зворотні косі риски завжди спиймаються буквально, напр. \\ і \'.
МІТКА;
Поданий вище приклад виведе:
Приклад тексту з кількома рядками з використанням синтаксису nowdoc. Зворотні косі риски завжди спиймаються буквально, напр. \\ і \'.
Приклад #13 Текст nowdoc зі змінними всередині
<?php
class foo
{
public $foo;
public $bar;
function __construct()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'Петро';
echo <<<'EOT'
Мене звати $name. Я друкую $foo->foo.
Зараз я друкую {$foo->bar[1]}.
Має НЕ надрукуватись велика буква 'A': \x41
EOT;
?>
Поданий вище приклад виведе:
Мене звати $name. Я друкую $foo->foo. Зараз я друкую {$foo->bar[1]}. Має НЕ надрукуватись велику буква 'A': \x41
Приклад #14 Зі статичними даними
<?php
class foo {
public $bar = <<<'EOT'
bar
EOT;
}
?>
Якщо рядок (string) записано в лапках або в heredoc, то в нього можна вставляти змінні.
Є два способи запису: основний та розширений. Основний синтаксис є найпоширенішим і найзручнішим. Він надає можливість вбудувати змінну, значення масиву (array), або властивість об'єкта (object) в рядок (string) з невеликими зусиллями.
Якщо трапляється знак долара ($
), а після — символи, що
є допустимими у назві змінної, то така послідовність вважається, власне,
змінною, а в текст замість неї підставляється її рядкове значення.
<?php
$фрукт = "персик";
echo "Він з'їв $фрукт." . PHP_EOL;
?>
Поданий вище приклад виведе:
Він з'їв персик.
Формально, структура основного синтаксису підставлення змінних є такою:
рядкова-змінна:: назва-змінної (зміщення-або-властивість)? | ${ вираз } зміщення-або-властивість:: зміщення-в-рядку | властивість-в-рядку зміщення-в-рядкуg:: [ назва ] | [ назва-змінної ] | [ цифровий-літерал ] властивість-в-рядку:: -> назва назва-змінної:: $ назва назва:: [a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*
Синтаксис ${ вираз }
є застарілим, починаючи з PHP
8.2.0, оскільки його можна інтерпретувати як
змінну змінної:
<?php
const foo = 'bar';
$foo = 'foo';
$bar = 'bar';
var_dump("${foo}");
var_dump("${(foo)}");
?>
В PHP 8.2 поданий вище приклад виведе:
Deprecated: Using ${var} in strings is deprecated, use {$var} instead in file on line 6 Deprecated: Using ${expr} (variable variables) in strings is deprecated, use {${expr}} instead in file on line 9 string(3) "foo" string(3) "bar"
Поданий вище приклад виведе:
string(3) "foo" string(3) "bar"
Зауваження: If it is not possible to form a valid name the dollar sign remains as verbatim in the string:
<?php
echo "No interpolation $ has happened\n";
echo "No interpolation $\n has happened\n";
echo "No interpolation $2 has happened\n";
?>Поданий вище приклад виведе:
No interpolation $ has happened No interpolation $ has happened No interpolation $2 has happened
Приклад #15 Interpolating the value of the first dimension of an array or property
<?php
$juices = array("apple", "orange", "string_key" => "purple");
echo "He drank some $juices[0] juice.";
echo PHP_EOL;
echo "He drank some $juices[1] juice.";
echo PHP_EOL;
echo "He drank some $juices[string_key] juice.";
echo PHP_EOL;
class A {
public $s = "string";
}
$o = new A();
echo "Object value: $o->s.";
?>
Поданий вище приклад виведе:
He drank some apple juice. He drank some orange juice. He drank some purple juice. Object value: string.
Зауваження: The array key must be unquoted, and it is therefore not possible to refer to a constant as a key with the basic syntax. Use the advanced syntax instead.
As of PHP 7.1.0 also negative numeric indices are supported.
Приклад #16 Negative numeric indices
<?php
$string = 'string';
echo "The character at index -2 is $string[-2].", PHP_EOL;
$string[-3] = 'o';
echo "Changing the character at index -3 to o gives $string.", PHP_EOL;
?>
Поданий вище приклад виведе:
The character at index -2 is n. Changing the character at index -3 to o gives strong.
For anything more complex, the advanced syntax must be used.
The advanced syntax permits the interpolation of variables with arbitrary accessors.
Any scalar variable, array element or object property
(static or not) with a
string representation can be included via this syntax.
The expression is written the same way as it would appear outside the
string, and then wrapped in {
and
}
. Since {
can not be escaped, this
syntax will only be recognised when the $
immediately
follows the {
. Use {\$
to get a
literal {$
. Some examples to make it clear:
<?php
const DATA_KEY = 'const-key';
$great = 'fantastic';
$arr = [
'1',
'2',
'3',
[41, 42, 43],
'key' => 'Indexed value',
'const-key' => 'Key with minus sign',
'foo' => ['foo1', 'foo2', 'foo3']
];
// Won't work, outputs: This is { fantastic}
echo "This is { $great}";
// Works, outputs: This is fantastic
echo "This is {$great}";
class Square {
public $width;
public function __construct(int $width) { $this->width = $width; }
}
$square = new Square(5);
// Works
echo "This square is {$square->width}00 centimeters wide.";
// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";
// Works
echo "This works: {$arr[3][2]}";
echo "This works: {$arr[DATA_KEY]}";
// When using multidimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][2]}";
echo "This works: {$obj->values[3]->name}";
echo "This works: {$obj->$staticProp}";
// Won't work, outputs: C:\folder\{fantastic}.txt
echo "C:\folder\{$great}.txt";
// Works, outputs: C:\folder\fantastic.txt
echo "C:\\folder\\{$great}.txt";
?>
Зауваження: As this syntax allows arbitrary expressions it is possible to use variable variables within the advanced syntax.
Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose. The functions substr() and substr_replace() can be used when you want to extract or replace more than 1 character.
Зауваження: As of PHP 7.1.0, negative string offsets are also supported. These specify the offset from the end of the string. Formerly, negative offsets emitted
E_NOTICE
for reading (yielding an empty string) andE_WARNING
for writing (leaving the string untouched).
Зауваження: Prior to PHP 8.0.0, strings could also be accessed using braces, as in $str{42}, for the same purpose. This curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.
Writing to an out of range offset pads the string with spaces.
Non-integer types are converted to integer.
Illegal offset type emits E_WARNING
.
Only the first character of an assigned string is used.
As of PHP 7.1.0, assigning an empty string throws a fatal error. Formerly,
it assigned a NULL byte.
Internally, PHP strings are byte arrays. As a result, accessing or modifying a string using array brackets is not multi-byte safe, and should only be done with strings that are in a single-byte encoding such as ISO-8859-1.
Зауваження: As of PHP 7.1.0, applying the empty index operator on an empty string throws a fatal error. Formerly, the empty string was silently converted to an array.
Приклад #17 Some string examples
<?php
// Get the first character of a string
$str = 'This is a test.';
$first = $str[0];
// Get the third character of a string
$third = $str[2];
// Get the last character of a string.
$str = 'This is still a test.';
$last = $str[strlen($str)-1];
// Modify the last character of a string
$str = 'Look at the sea';
$str[strlen($str)-1] = 'e';
?>
String offsets have to either be integers or integer-like strings, otherwise a warning will be thrown.
Приклад #18 Example of Illegal String Offsets
<?php
$str = 'abc';
var_dump($str['1']);
var_dump(isset($str['1']));
var_dump($str['1.0']);
var_dump(isset($str['1.0']));
var_dump($str['x']);
var_dump(isset($str['x']));
var_dump($str['1x']);
var_dump(isset($str['1x']));
?>
Поданий вище приклад виведе:
string(1) "b" bool(true) Warning: Illegal string offset '1.0' in /tmp/t.php on line 7 string(1) "b" bool(false) Warning: Illegal string offset 'x' in /tmp/t.php on line 9 string(1) "a" bool(false) string(1) "b" bool(false)
Зауваження:
Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using
[]
or{}
silently returnsnull
.
Зауваження:
Characters within string literals can be accessed using
[]
or{}
.
Зауваження:
Accessing characters within string literals using the
{}
syntax has been deprecated in PHP 7.4. This has been removed in PHP 8.0.
Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. See String operators for more information.
There are a number of useful functions for string manipulation.
See the string functions section for general functions, and the Perl-compatible regular expression functions for advanced find & replace functionality.
There are also functions for URL strings, and functions to encrypt/decrypt strings (Sodium and Hash).
Finally, see also the character type functions.
A value can be converted to a string using the
(string)
cast or the strval() function.
String conversion is automatically done in the scope of an
expression where a string is needed. This happens when using the
echo or print functions, or when a
variable is compared to a string. The sections on
Types and
Type Juggling will make
the following clearer. See also the settype() function.
A bool true
value is converted to the string
"1"
. bool false
is converted to
""
(the empty string). This allows conversion back and
forth between bool and string values.
An int or float is converted to a
string representing the number textually (including the
exponent part for floats). Floating point numbers can be
converted using exponential notation (4.1E+6
).
Зауваження:
As of PHP 8.0.0, the decimal point character is always a period ("
.
"). Prior to PHP 8.0.0, the decimal point character is defined in the script's locale (category LC_NUMERIC). See the setlocale() function.
Arrays are always converted to the string
"Array"
; because of this, echo and
print can not by themselves show the contents of an
array. To view a single element, use a construction such as
echo $arr['foo']
. See below for tips on viewing the entire
contents.
In order to convert objects to string, the magic method __toString must be used.
Resources are always converted to strings with the
structure "Resource id #1"
, where 1
is the resource number assigned to the resource by PHP at
runtime. While the exact structure of this string should not be relied on
and is subject to change, it will always be unique for a given resource
within the lifetime of a script being executed (ie a Web request or CLI
process) and won't be reused. To get a resource's type, use
the get_resource_type() function.
null
is always converted to an empty string.
As stated above, directly converting an array, object, or resource to a string does not provide any useful information about the value beyond its type. See the functions print_r() and var_dump() for more effective means of inspecting the contents of these types.
Most PHP values can also be converted to strings for permanent storage. This method is called serialization, and is performed by the serialize() function.
The string in PHP is implemented as an array of bytes and an
integer indicating the length of the buffer. It has no information about how
those bytes translate to characters, leaving that task to the programmer.
There are no limitations on the values the string can be composed of; in
particular, bytes with value 0
(“NUL bytes”) are allowed
anywhere in the string (however, a few functions, said in this manual not to
be “binary safe”, may hand off the strings to libraries that ignore data
after a NUL byte.)
This nature of the string type explains why there is no separate “byte” type in PHP – strings take this role. Functions that return no textual data – for instance, arbitrary data read from a network socket – will still return strings.
Given that PHP does not dictate a specific encoding for strings, one might
wonder how string literals are encoded. For instance, is the string
"á"
equivalent to "\xE1"
(ISO-8859-1),
"\xC3\xA1"
(UTF-8, C form),
"\x61\xCC\x81"
(UTF-8, D form) or any other possible
representation? The answer is that string will be encoded in whatever fashion
it is encoded in the script file. Thus, if the script is written in
ISO-8859-1, the string will be encoded in ISO-8859-1 and so on. However,
this does not apply if Zend Multibyte is enabled; in that case, the script
may be written in an arbitrary encoding (which is explicitly declared or is
detected) and then converted to a certain internal encoding, which is then
the encoding that will be used for the string literals.
Note that there are some constraints on the encoding of the script (or on the
internal encoding, should Zend Multibyte be enabled) – this almost always
means that this encoding should be a compatible superset of ASCII, such as
UTF-8 or ISO-8859-1. Note, however, that state-dependent encodings where
the same byte values can be used in initial and non-initial shift states
may be problematic.
Of course, in order to be useful, functions that operate on text may have to make some assumptions about how the string is encoded. Unfortunately, there is much variation on this matter throughout PHP’s functions:
u
modifier is used).
Ultimately, this means writing correct programs using Unicode depends on carefully avoiding functions that will not work and that most likely will corrupt the data and using instead the functions that do behave correctly, generally from the intl and mbstring extensions. However, using functions that can handle Unicode encodings is just the beginning. No matter the functions the language provides, it is essential to know the Unicode specification. For instance, a program that assumes there is only uppercase and lowercase is making a wrong assumption.