1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
|
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<sect1 xml:id="language.types.string">
<title>Strings</title>
<para>
A <type>string</type> is a series of characters, where a character is
the same as a byte. This means that PHP only supports a 256-character set,
and hence does not offer native Unicode support. See
<link linkend="language.types.string.details">details of the string
type</link>.
</para>
<note>
<simpara>
On 32-bit builds, a <type>string</type> can be as large as up to 2GB
(2147483647 bytes maximum)
</simpara>
</note>
<sect2 xml:id="language.types.string.syntax">
<title>Syntax</title>
<para>
A <type>string</type> literal can be specified in four different ways:
</para>
<itemizedlist>
<listitem>
<simpara>
<link linkend="language.types.string.syntax.single">single quoted</link>
</simpara>
</listitem>
<listitem>
<simpara>
<link linkend="language.types.string.syntax.double">double quoted</link>
</simpara>
</listitem>
<listitem>
<simpara>
<link linkend="language.types.string.syntax.heredoc">heredoc syntax</link>
</simpara>
</listitem>
<listitem>
<simpara>
<link linkend="language.types.string.syntax.nowdoc">nowdoc syntax</link>
</simpara>
</listitem>
</itemizedlist>
<sect3 xml:id="language.types.string.syntax.single">
<title>Single quoted</title>
<para>
The simplest way to specify a <type>string</type> is to enclose it in single
quotes (the character <literal>'</literal>).
</para>
<para>
To specify a literal single quote, escape it with a backslash
(<literal>\</literal>). To specify a literal backslash, double it
(<literal>\\</literal>). All other instances of backslash will be treated
as a literal backslash: this means that the other escape sequences you
might be used to, such as <literal>\r</literal> or <literal>\n</literal>,
will be output literally as specified rather than having any special
meaning.
</para>
<note>
<simpara>
Unlike the <link linkend="language.types.string.syntax.double">double-quoted</link>
and <link linkend="language.types.string.syntax.heredoc">heredoc</link> syntaxes,
<link linkend="language.variables">variables</link> and escape sequences
for special characters will <emphasis>not</emphasis> be expanded when they
occur in single quoted <type>string</type>s.
</simpara>
</note>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
echo 'this is a simple string';
echo 'You can also have embedded newlines in
strings this way as it is
okay to do';
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';
// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';
// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>
]]>
</programlisting>
</informalexample>
</sect3>
<sect3 xml:id="language.types.string.syntax.double">
<title>Double quoted</title>
<para>
If the <type>string</type> is enclosed in double-quotes (<literal>"</literal>), PHP will
interpret the following escape sequences for special characters:
</para>
<table>
<title>Escaped characters</title>
<tgroup cols="2">
<thead>
<row>
<entry>Sequence</entry>
<entry>Meaning</entry>
</row>
</thead>
<tbody>
<row>
<entry><literal>\n</literal></entry>
<entry>linefeed (LF or 0x0A (10) in ASCII)</entry>
</row>
<row>
<entry><literal>\r</literal></entry>
<entry>carriage return (CR or 0x0D (13) in ASCII)</entry>
</row>
<row>
<entry><literal>\t</literal></entry>
<entry>horizontal tab (HT or 0x09 (9) in ASCII)</entry>
</row>
<row>
<entry><literal>\v</literal></entry>
<entry>vertical tab (VT or 0x0B (11) in ASCII)</entry>
</row>
<row>
<entry><literal>\e</literal></entry>
<entry>escape (ESC or 0x1B (27) in ASCII)</entry>
</row>
<row>
<entry><literal>\f</literal></entry>
<entry>form feed (FF or 0x0C (12) in ASCII)</entry>
</row>
<row>
<entry><literal>\\</literal></entry>
<entry>backslash</entry>
</row>
<row>
<entry><literal>\$</literal></entry>
<entry>dollar sign</entry>
</row>
<row>
<entry><literal>\"</literal></entry>
<entry>double-quote</entry>
</row>
<row>
<entry><literal>\[0-7]{1,3}</literal></entry>
<entry>
Octal: the sequence of characters matching the regular expression <literal>[0-7]{1,3}</literal>
is a character in octal notation (e.g. <literal>"\101" === "A"</literal>),
which silently overflows to fit in a byte (e.g. <literal>"\400" === "\000"</literal>)
</entry>
</row>
<row>
<entry><literal>\x[0-9A-Fa-f]{1,2}</literal></entry>
<entry>
Hexadecimal: the sequence of characters matching the regular expression
<literal>[0-9A-Fa-f]{1,2}</literal> is a character in hexadecimal notation
(e.g. <literal>"\x41" === "A"</literal>)
</entry>
</row>
<row>
<entry><literal>\u{[0-9A-Fa-f]+}</literal></entry>
<entry>
Unicode: the sequence of characters matching the regular expression <literal>[0-9A-Fa-f]+</literal>
is a Unicode codepoint, which will be output to the string as that codepoint's UTF-8 representation.
The braces are required in the sequence. E.g. <literal>"\u{41}" === "A"</literal>
</entry>
</row>
</tbody>
</tgroup>
</table>
<para>
As in single quoted <type>string</type>s, escaping any other character will
result in the backslash being printed too.
</para>
<para>
The most important feature of double-quoted <type>string</type>s is the fact
that variable names will be expanded. See
<link linkend="language.types.string.parsing">string interpolation</link> for
details.
</para>
</sect3>
<sect3 xml:id="language.types.string.syntax.heredoc">
<title>Heredoc</title>
<simpara>
A third way to delimit <type>string</type>s is the heredoc syntax:
<literal><<<</literal>. After this operator, an identifier is
provided, then a newline. The <type>string</type> itself follows, and then
the same identifier again to close the quotation.
</simpara>
<simpara>
The closing identifier may be indented by space or tab, in which case
the indentation will be stripped from all lines in the doc string.
Prior to PHP 7.3.0, the closing identifier <emphasis>must</emphasis>
begin in the first column of the line.
</simpara>
<simpara>
Also, the closing identifier must follow the same naming rules as any
other label in PHP: it must contain only alphanumeric characters and
underscores, and must start with a non-digit character or underscore.
</simpara>
<example>
<title>Basic Heredoc example as of PHP 7.3.0</title>
<programlisting role="php">
<![CDATA[
<?php
// no indentation
echo <<<END
a
b
c
\n
END;
// 4 spaces of indentation
echo <<<END
a
b
c
END;
]]>
</programlisting>
&example.outputs.73;
<screen>
<![CDATA[
a
b
c
a
b
c
]]>
</screen>
</example>
<simpara>
If the closing identifier is indented further than any lines of the body, then a <classname>ParseError</classname> will be thrown:
</simpara>
<example>
<title>Closing identifier must not be indented further than any lines of the body</title>
<programlisting role="php">
<![CDATA[
<?php
echo <<<END
a
b
c
END;
]]>
</programlisting>
&example.outputs.73;
<screen>
<![CDATA[
PHP Parse error: Invalid body indentation level (expecting an indentation level of at least 3) in example.php on line 4
]]>
</screen>
</example>
<simpara>
If the closing identifier is indented, tabs can be used as well, however,
tabs and spaces <emphasis>must not</emphasis> be intermixed regarding
the indentation of the closing identifier and the indentation of the body
(up to the closing identifier). In any of these cases, a <classname>ParseError</classname> will be thrown.
These whitespace constraints have been included because mixing tabs and
spaces for indentation is harmful to legibility.
</simpara>
<example>
<title>Different indentation for body (spaces) closing identifier</title>
<programlisting role="php">
<![CDATA[
<?php
// All the following code do not work.
// different indentation for body (spaces) ending marker (tabs)
{
echo <<<END
a
END;
}
// mixing spaces and tabs in body
{
echo <<<END
a
END;
}
// mixing spaces and tabs in ending marker
{
echo <<<END
a
END;
}
]]>
</programlisting>
&example.outputs.73;
<screen>
<![CDATA[
PHP Parse error: Invalid indentation - tabs and spaces cannot be mixed in example.php line 8
]]>
</screen>
</example>
<simpara>
The closing identifier for the body string is not required to be
followed by a semicolon or newline. For example, the following code
is allowed as of PHP 7.3.0:
</simpara>
<example>
<title>Continuing an expression after a closing identifier</title>
<programlisting role="php">
<![CDATA[
<?php
$values = [<<<END
a
b
c
END, 'd e f'];
var_dump($values);
]]>
</programlisting>
&example.outputs.73;
<screen>
<![CDATA[
array(2) {
[0] =>
string(11) "a
b
c"
[1] =>
string(5) "d e f"
}
]]>
</screen>
</example>
<warning>
<simpara>
If the closing identifier was found at the start of a line, then
regardless of whether it was a part of another word, it may be considered
as the closing identifier and causes a <classname>ParseError</classname>.
</simpara>
<example>
<title>Closing identifier in body of the string tends to cause ParseError</title>
<programlisting role="php">
<![CDATA[
<?php
$values = [<<<END
a
b
END ING
END, 'd e f'];
]]>
</programlisting>
&example.outputs.73;
<screen>
<![CDATA[
PHP Parse error: syntax error, unexpected identifier "ING", expecting "]" in example.php on line 6
]]>
</screen>
</example>
<simpara>
To avoid this problem, it is safe to follow the simple rule:
<emphasis>do not choose as a closing identifier if it appears in the body
of the text</emphasis>.
</simpara>
</warning>
<warning>
<simpara>
Prior to PHP 7.3.0, it is very important to note that the line with the
closing identifier must contain no other characters, except a semicolon
(<literal>;</literal>).
That means especially that the identifier
<emphasis>may not be indented</emphasis>, and there may not be any spaces
or tabs before or after the semicolon. It's also important to realize that
the first character before the closing identifier must be a newline as
defined by the local operating system. This is <literal>\n</literal> on
UNIX systems, including macOS. The closing delimiter must also be
followed by a newline.
</simpara>
<simpara>
If this rule is broken and the closing identifier is not "clean", it will
not be considered a closing identifier, and PHP will continue looking for
one. If a proper closing identifier is not found before the end of the
current file, a parse error will result at the last line.
</simpara>
<example>
<title>Invalid example, prior to PHP 7.3.0</title>
<programlisting role="php">
<!-- This is an INVALID example -->
<![CDATA[
<?php
class foo {
public $bar = <<<EOT
bar
EOT;
}
// Identifier must not be indented
?>
]]>
</programlisting>
</example>
<example>
<title>Valid example, even prior to PHP 7.3.0</title>
<programlisting role="php">
<!-- This is a VALID example -->
<![CDATA[
<?php
class foo {
public $bar = <<<EOT
bar
EOT;
}
?>
]]>
</programlisting>
</example>
<para>
Heredocs containing variables can not be used for initializing class properties.
</para>
</warning>
<para>
Heredoc text behaves just like a double-quoted <type>string</type>, without
the double quotes. This means that quotes in a heredoc do not need to be
escaped, but the escape codes listed above can still be used. Variables are
expanded, but the same care must be taken when expressing complex variables
inside a heredoc as with <type>string</type>s.
</para>
<example>
<title>Heredoc string quoting example</title>
<programlisting role="php">
<![CDATA[
<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
/* More complex example, with variables. */
class foo
{
var $foo;
var $bar;
function __construct()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'MyName';
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
My name is "MyName". I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital 'A': A]]>
</screen>
</example>
<para>
It is also possible to use the Heredoc syntax to pass data to function
arguments:
</para>
<example>
<title>Heredoc in arguments example</title>
<programlisting role="php">
<![CDATA[
<?php
var_dump(array(<<<EOD
foobar!
EOD
));
?>
]]>
</programlisting>
</example>
<para>
It's possible to initialize static variables and class
properties/constants using the Heredoc syntax:
</para>
<example>
<title>Using Heredoc to initialize static values</title>
<programlisting role="php">
<![CDATA[
<?php
// Static variables
function foo()
{
static $bar = <<<LABEL
Nothing in here...
LABEL;
}
// Class properties/constants
class foo
{
const BAR = <<<FOOBAR
Constant example
FOOBAR;
public $baz = <<<FOOBAR
Property example
FOOBAR;
}
?>
]]>
</programlisting>
</example>
<para>
The opening Heredoc identifier may optionally be
enclosed in double quotes:
</para>
<example>
<title>Using double quotes in Heredoc</title>
<programlisting role="php">
<![CDATA[
<?php
echo <<<"FOOBAR"
Hello World!
FOOBAR;
?>
]]>
</programlisting>
</example>
</sect3>
<sect3 xml:id="language.types.string.syntax.nowdoc">
<title>Nowdoc</title>
<para>
Nowdocs are to single-quoted strings what heredocs are to double-quoted
strings. A nowdoc is specified similarly to a heredoc, but <emphasis>no
String interpolation is done</emphasis> inside a nowdoc. The construct is ideal for
embedding PHP code or other large blocks of text without the need for
escaping. It shares some features in common with the SGML
<literal><![CDATA[ ]]></literal> construct, in that it declares a
block of text which is not for parsing.
</para>
<para>
A nowdoc is identified with the same <literal><<<</literal>
sequence used for heredocs, but the identifier which follows is enclosed in
single quotes, e.g. <literal><<<'EOT'</literal>. All the rules for
heredoc identifiers also apply to nowdoc identifiers, especially those
regarding the appearance of the closing identifier.
</para>
<example>
<title>Nowdoc string quoting example</title>
<programlisting role="php">
<![CDATA[
<?php
echo <<<'EOD'
Example of string spanning multiple lines
using nowdoc syntax. Backslashes are always treated literally,
e.g. \\ and \'.
EOD;
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Example of string spanning multiple lines
using nowdoc syntax. Backslashes are always treated literally,
e.g. \\ and \'.
]]>
</screen>
</example>
<example>
<title>Nowdoc string quoting example with variables</title>
<programlisting role="php">
<![CDATA[
<?php
class foo
{
public $foo;
public $bar;
function __construct()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'MyName';
echo <<<'EOT'
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41
EOT;
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41]]>
</screen>
</example>
<example>
<title>Static data example</title>
<programlisting role="php">
<![CDATA[
<?php
class foo {
public $bar = <<<'EOT'
bar
EOT;
}
?>
]]>
</programlisting>
</example>
</sect3>
<sect3 xml:id="language.types.string.parsing">
<title>String interpolation</title>
<simpara>
When a <type>string</type> is specified in double quotes or with heredoc,
<link linkend="language.variables">variables</link> can be substituted within it.
</simpara>
<simpara>
There are two types of syntax: a
<link linkend="language.types.string.parsing.basic">basic</link> one and an
<link linkend="language.types.string.parsing.advanced">advanced</link> one.
The basic syntax is the most common and convenient. It provides a way to
embed a variable, an <type>array</type> value, or an <type>object</type>
property in a <type>string</type> with a minimum of effort.
</simpara>
<sect4 xml:id="language.types.string.parsing.basic">
<title>Basic syntax</title>
<simpara>
If a dollar sign (<literal>$</literal>) is encountered, the characters
that follow it which can be used in a variable name will be interpreted
as such and substituted.
</simpara>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$juice = "apple";
echo "He drank some $juice juice." . PHP_EOL;
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
He drank some apple juice.
]]>
</screen>
</informalexample>
<simpara>
Formally, the structure for the basic variable substitution syntax is
as follows:
</simpara>
<informalexample>
<programlisting>
<![CDATA[
string-variable::
variable-name (offset-or-property)?
| ${ expression }
offset-or-property::
offset-in-string
| property-in-string
offset-in-string::
[ name ]
| [ variable-name ]
| [ integer-literal ]
property-in-string::
-> name
variable-name::
$ name
name::
[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*
]]>
</programlisting>
</informalexample>
<warning>
<para>
The <literal>${ expression }</literal> syntax is deprecated as of
PHP 8.2.0, as it can be interpreted as
<link linkend="language.variables.variable">variable variables</link>:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
const foo = 'bar';
$foo = 'foo';
$bar = 'bar';
var_dump("${foo}");
var_dump("${(foo)}");
?>
]]>
</programlisting>
&example.outputs.82;
<screen>
<![CDATA[
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"
]]>
</screen>
&example.outputs;
<screen>
<![CDATA[
string(3) "foo"
string(3) "bar"
]]>
</screen>
</informalexample>
The <link linkend="language.types.string.parsing.advanced">advanced</link>
string interpolation syntax should be used instead.
</para>
</warning>
<note>
<simpara>
If it is not possible to form a valid name the dollar sign remains
as verbatim in the string:
</simpara>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
echo "No interpolation $ has happened\n";
echo "No interpolation $\n has happened\n";
echo "No interpolation $2 has happened\n";
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
No interpolation $ has happened
No interpolation $
has happened
No interpolation $2 has happened
]]>
</screen>
</informalexample>
</note>
<example>
<title>Interpolating the value of the first dimension of an array or property</title>
<programlisting role="php">
<![CDATA[
<?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.";
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
He drank some apple juice.
He drank some orange juice.
He drank some purple juice.
Object value: string.
]]>
</screen>
</example>
<note>
<simpara>
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
<link linkend="language.types.string.parsing.advanced">advanced</link>
syntax instead.
</simpara>
</note>
<simpara>
As of PHP 7.1.0 also <emphasis>negative</emphasis> numeric indices are
supported.
</simpara>
<example><title>Negative numeric indices</title>
<programlisting role="php">
<![CDATA[
<?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;
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
The character at index -2 is n.
Changing the character at index -3 to o gives strong.
]]>
</screen>
</example>
<simpara>
For anything more complex, the
<link linkend="language.types.string.parsing.advanced">advanced</link>
syntax must be used.
</simpara>
</sect4>
<sect4 xml:id="language.types.string.parsing.advanced">
<title>Advanced (curly) syntax</title>
<simpara>
The advanced syntax permits the interpolation of
<emphasis>variables</emphasis> with arbitrary accessors.
</simpara>
<simpara>
Any scalar variable, array element or object property
(<modifier>static</modifier> or not) with a
<type>string</type> representation can be included via this syntax.
The expression is written the same way as it would appear outside the
<type>string</type>, and then wrapped in <literal>{</literal> and
<literal>}</literal>. Since <literal>{</literal> can not be escaped, this
syntax will only be recognised when the <literal>$</literal> immediately
follows the <literal>{</literal>. Use <literal>{\$</literal> to get a
literal <literal>{$</literal>. Some examples to make it clear:
</simpara>
<informalexample>
<programlisting role="php">
<![CDATA[
<?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";
?>
]]>
</programlisting>
</informalexample>
<note>
<simpara>
As this syntax allows arbitrary expressions it is possible to use
<link linkend="language.variables.variable">variable variables</link>
within the advanced syntax.
</simpara>
</note>
</sect4>
</sect3>
<sect3 xml:id="language.types.string.substr">
<title>String access and modification by character</title>
<para>
Characters within <type>string</type>s may be accessed and modified by
specifying the zero-based offset of the desired character after the
<type>string</type> using square <type>array</type> brackets, as in
<varname>$str[42]</varname>. Think of a <type>string</type> as an
<type>array</type> of characters for this purpose. The functions
<function>substr</function> and <function>substr_replace</function>
can be used when you want to extract or replace more than 1 character.
</para>
<note>
<simpara>
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 <constant>E_NOTICE</constant> for reading
(yielding an empty string) and <constant>E_WARNING</constant> for writing
(leaving the string untouched).
</simpara>
</note>
<note>
<simpara>
Prior to PHP 8.0.0, <type>string</type>s could also be accessed using braces, as in
<varname>$str{42}</varname>, 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.
</simpara>
</note>
<warning>
<simpara>
Writing to an out of range offset pads the string with spaces.
Non-integer types are converted to integer.
Illegal offset type emits <constant>E_WARNING</constant>.
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.
</simpara>
</warning>
<warning>
<simpara>
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.
</simpara>
</warning>
<note>
<simpara>
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.
</simpara>
</note>
<example>
<title>Some string examples</title>
<programlisting role="php">
<![CDATA[
<?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';
?>
]]>
</programlisting>
</example>
<para>
String offsets have to either be integers or integer-like strings,
otherwise a warning will be thrown.
</para>
<example>
<!-- TODO Update for PHP 8.0 -->
<title>Example of Illegal String Offsets</title>
<programlisting role="php">
<![CDATA[
<?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']));
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
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)
]]>
</screen>
</example>
<note>
<para>
Accessing variables of other types (not including arrays or objects
implementing the appropriate interfaces) using <literal>[]</literal> or
<literal>{}</literal> silently returns &null;.
</para>
</note>
<note>
<para>
Characters within string literals can be accessed
using <literal>[]</literal> or <literal>{}</literal>.
</para>
</note>
<note>
<para>
Accessing characters within string literals using the
<literal>{}</literal> syntax has been deprecated in PHP 7.4.
This has been removed in PHP 8.0.
</para>
</note>
</sect3>
</sect2><!-- end syntax -->
<sect2 xml:id="language.types.string.useful-funcs">
<title>Useful functions and operators</title>
<para>
<type>String</type>s may be concatenated using the '.' (dot) operator. Note
that the '+' (addition) operator will <emphasis>not</emphasis> work for this.
See <link linkend="language.operators.string">String operators</link> for
more information.
</para>
<para>
There are a number of useful functions for <type>string</type> manipulation.
</para>
<simpara>
See the <link linkend="ref.strings">string functions section</link> for
general functions, and the <link linkend="ref.pcre">Perl-compatible regular
expression functions</link> for advanced find & replace functionality.
</simpara>
<simpara>
There are also <link linkend="ref.url">functions for URL strings</link>, and
functions to encrypt/decrypt strings
(<link linkend="ref.sodium">Sodium</link> and
<link linkend="ref.hash">Hash</link>).
</simpara>
<simpara>
Finally, see also the <link linkend="ref.ctype">character type
functions</link>.
</simpara>
</sect2>
<sect2 xml:id="language.types.string.casting">
<title>Converting to string</title>
<para>
A value can be converted to a <type>string</type> using the
<literal>(string)</literal> cast or the <function>strval</function> function.
<type>String</type> conversion is automatically done in the scope of an
expression where a <type>string</type> is needed. This happens when using the
<function>echo</function> or <function>print</function> functions, or when a
variable is compared to a <type>string</type>. The sections on
<link linkend="language.types">Types</link> and
<link linkend="language.types.type-juggling">Type Juggling</link> will make
the following clearer. See also the <function>settype</function> function.
</para>
<para>
A <type>bool</type> &true; value is converted to the <type>string</type>
<literal>"1"</literal>. <type>bool</type> &false; is converted to
<literal>""</literal> (the empty string). This allows conversion back and
forth between <type>bool</type> and <type>string</type> values.
</para>
<para>
An <type>int</type> or <type>float</type> is converted to a
<type>string</type> representing the number textually (including the
exponent part for <type>float</type>s). Floating point numbers can be
converted using exponential notation (<literal>4.1E+6</literal>).
</para>
<note>
<para>
As of PHP 8.0.0, the decimal point character is always
a period ("<literal>.</literal>"). Prior to PHP 8.0.0,
the decimal point character is defined in the script's locale (category
LC_NUMERIC). See the <function>setlocale</function> function.
</para>
</note>
<para>
<type>Array</type>s are always converted to the <type>string</type>
<literal>"Array"</literal>; because of this, <function>echo</function> and
<function>print</function> can not by themselves show the contents of an
<type>array</type>. To view a single element, use a construction such as
<literal>echo $arr['foo']</literal>. See below for tips on viewing the entire
contents.
</para>
<para>
In order to convert <type>object</type>s to <type>string</type>, the magic
method <link linkend="language.oop5.magic">__toString</link> must be used.
</para>
<para>
<type>Resource</type>s are always converted to <type>string</type>s with the
structure <literal>"Resource id #1"</literal>, where <literal>1</literal>
is the resource number assigned to the <type>resource</type> 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 <type>resource</type>'s type, use
the <function>get_resource_type</function> function.
</para>
<para>
&null; is always converted to an empty string.
</para>
<para>
As stated above, directly converting an <type>array</type>,
<type>object</type>, or <type>resource</type> to a <type>string</type> does
not provide any useful information about the value beyond its type. See the
functions <function>print_r</function> and <function>var_dump</function> for
more effective means of inspecting the contents of these types.
</para>
<para>
Most PHP values can also be converted to <type>string</type>s for permanent
storage. This method is called serialization, and is performed by the
<function>serialize</function> function.
</para>
</sect2>
<sect2 xml:id="language.types.string.details">
<title>Details of the String Type</title>
<para>
The <type>string</type> 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 <literal>0</literal> (“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.)
</para>
<para>
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.
</para>
<para>
Given that PHP does not dictate a specific encoding for strings, one might
wonder how string literals are encoded. For instance, is the string
<literal>"á"</literal> equivalent to <literal>"\xE1"</literal> (ISO-8859-1),
<literal>"\xC3\xA1"</literal> (UTF-8, C form),
<literal>"\x61\xCC\x81"</literal> (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.
</para>
<para>
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:
</para>
<itemizedlist>
<listitem>
<simpara>
Some functions assume that the string is encoded in some (any) single-byte
encoding, but they do not need to interpret those bytes as specific
characters. This is case of, for instance, <function>substr</function>,
<function>strpos</function>, <function>strlen</function> or
<function>strcmp</function>. Another way to think of these functions is
that operate on memory buffers, i.e., they work with bytes and byte
offsets.
</simpara>
</listitem>
<listitem>
<simpara>
Other functions are passed the encoding of the string, possibly they also
assume a default if no such information is given. This is the case of
<function>htmlentities</function> and the majority of the
functions in the <link linkend="book.mbstring">mbstring</link> extension.
</simpara>
</listitem>
<listitem>
<simpara>
Others use the current locale (see <function>setlocale</function>), but
operate byte-by-byte.
</simpara>
</listitem>
<listitem>
<simpara>
Finally, they may just assume the string is using a specific encoding,
usually UTF-8. This is the case of most functions in the
<link linkend="book.intl">intl</link> extension and in the
<link linkend="book.pcre">PCRE</link> extension
(in the last case, only when the <literal>u</literal> modifier is used).
</simpara>
</listitem>
</itemizedlist>
<para>
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 <link linkend="book.intl">intl</link> and
<link linkend="book.mbstring">mbstring</link> 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.
</para>
</sect2>
</sect1><!-- end string -->
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
|