SunshinePHP Developer Conference 2015

Strings

A string is 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 details of the string type.

Notă: string can be as large as up to 2GB (2147483647 bytes maximum)

Syntax

A string literal can be specified in four different ways:

Single quoted

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

To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash, double it (\\). 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 \r or \n, will be output literally as specified rather than having any special meaning.

Notă: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

<?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';
?>

Double quoted

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

Escaped characters
Sequence Meaning
\n linefeed (LF or 0x0A (10) in ASCII)
\r carriage return (CR or 0x0D (13) in ASCII)
\t horizontal tab (HT or 0x09 (9) in ASCII)
\v vertical tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5)
\e escape (ESC or 0x1B (27) in ASCII) (since PHP 5.4.0)
\f form feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
\\ backslash
\$ dollar sign
\" double-quote
\[0-7]{1,3} the sequence of characters matching the regular expression is a character in octal notation
\x[0-9A-Fa-f]{1,2} the sequence of characters matching the regular expression is a character in hexadecimal notation

As in single quoted strings, escaping any other character will result in the backslash being printed too. Before PHP 5.1.1, the backslash in \{$var} had not been printed.

The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.

Heredoc

A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.

The closing identifier must begin in the first column of the line. Also, the 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.

Avertizare

It is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (;). That means especially that the identifier may not be indented, 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 \n on UNIX systems, including Mac OS X. The closing delimiter must also be followed by a newline.

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.

Heredocs can not be used for initializing class properties. Since PHP 5.3, this limitation is valid only for heredocs containing variables.

Example #1 Invalid example

<?php
class foo {
    public 
$bar = <<<EOT
bar
    EOT;
}
?>

Heredoc text behaves just like a double-quoted string, 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 strings.

Example #2 Heredoc string quoting example

<?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 
foo()
    {
        
$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;
?>

Exemplul de mai sus va afișa:

My name is "MyName". I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital 'A': A

It is also possible to use the Heredoc syntax to pass data to function arguments:

Example #3 Heredoc in arguments example

<?php
var_dump
(array(<<<EOD
foobar!
EOD
));
?>

As of PHP 5.3.0, it's possible to initialize static variables and class properties/constants using the Heredoc syntax:

Example #4 Using Heredoc to initialize static values

<?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;
}
?>

Starting with PHP 5.3.0, the opening Heredoc identifier may optionally be enclosed in double quotes:

Example #5 Using double quotes in Heredoc

<?php
echo <<<"FOOBAR"
Hello World!
FOOBAR;
?>

Nowdoc

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done 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 <![CDATA[ ]]> construct, in that it declares a block of text which is not for parsing.

A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.

Example #6 Nowdoc string quoting example

<?php
$str 
= <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;

/* More complex example, with variables. */
class foo
{
    public 
$foo;
    public 
$bar;

    function 
foo()
    {
        
$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;
?>

Exemplul de mai sus va afișa:

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

Notă:

Unlike heredocs, nowdocs can be used in any static data context. The typical example is initializing class properties or constants:

Example #7 Static data example

<?php
class foo {
    public 
$bar = <<<'EOT'
bar
EOT;
}
?>

Notă:

Nowdoc support was added in PHP 5.3.0.

Variable parsing

When a string is specified in double quotes or with heredoc, variables are parsed within it.

There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort.

The complex syntax can be recognised by the curly braces surrounding the expression.

Simple syntax

If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.

<?php
$juice 
"apple";

echo 
"He drank some $juice juice.".PHP_EOL;
// Invalid. "s" is a valid character for a variable name, but the variable is $juice.
echo "He drank some juice made of $juices.";
?>

Exemplul de mai sus va afișa:

He drank some apple juice.
He drank some juice made of .

Similarly, an array index or an object property can be parsed. With array indices, the closing square bracket (]) marks the end of the index. The same rules apply to object properties as to simple variables.

Example #8 Simple syntax example

<?php
$juices 
= array("apple""orange""koolaid1" => "purple");

echo 
"He drank some $juices[0] juice.".PHP_EOL;
echo 
"He drank some $juices[1] juice.".PHP_EOL;
echo 
"He drank some $juices[koolaid1] juice.".PHP_EOL;

class 
people {
    public 
$john "John Smith";
    public 
$jane "Jane Smith";
    public 
$robert "Robert Paulsen";
    
    public 
$smith "Smith";
}

$people = new people();

echo 
"$people->john drank some $juices[0] juice.".PHP_EOL;
echo 
"$people->john then said hello to $people->jane.".PHP_EOL;
echo 
"$people->john's wife greeted $people->robert.".PHP_EOL;
echo 
"$people->robert greeted the two $people->smiths."// Won't work
?>

Exemplul de mai sus va afișa:

He drank some apple juice.
He drank some orange juice.
He drank some purple juice.
John Smith drank some apple juice.
John Smith then said hello to Jane Smith.
John Smith's wife greeted Robert Paulsen.
Robert Paulsen greeted the two .

For anything more complex, you should use the complex syntax.

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it 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
// Show all errors
error_reporting(E_ALL);

$great 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo 
"This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad."


// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";


// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong  outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}"

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " $arr['foo'][3];

echo 
"This works too: {$obj->values[3]->name}";

echo 
"This is the value of the var named $name{${$name}}";

echo 
"This is the value of the var named by the return value of getName(): {${getName()}}";

echo 
"This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";

// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>

It is also possible to access class properties using variables within strings using this syntax.

<?php
class foo {
    var 
$bar 'I am bar.';
}

$foo = new foo();
$bar 'bar';
$baz = array('foo''bar''baz''quux');
echo 
"{$foo->$bar}\n";
echo 
"{$foo->$baz[1]}\n";
?>

Exemplul de mai sus va afișa:

I am bar.
I am bar.

Notă:

Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.

<?php
// Show all errors.
error_reporting(E_ALL);

class 
beers {
    const 
softdrink 'rootbeer';
    public static 
$ale 'ipa';
}

$rootbeer 'A & W';
$ipa 'Alexander Keith\'s';

// This works; outputs: I'd like an A & W
echo "I'd like an {${beers::softdrink}}\n";

// This works too; outputs: I'd like an Alexander Keith's
echo "I'd like an {${beers::$ale}}\n";
?>

String access and modification by character

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.

Notă: Strings may also be accessed using braces, as in $str{42}, for the same purpose.

Avertizare

Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits E_NOTICE. Negative offset emits E_NOTICE in write but reads empty string. Only the first character of an assigned string is used. Assigning empty string assigns NULL byte.

Avertizare

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.

Example #9 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';

?>

As of PHP 5.4 string offsets have to either be integers or integer-like strings, otherwise a warning will be thrown. Previously an offset like "foo" was silently cast to 0.

Example #10 Differences between PHP 5.3 and PHP 5.4

<?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']));
?>

Exemplul de mai sus va afișa în PHP 5.3:

string(1) "b"
bool(true)
string(1) "b"
bool(true)
string(1) "a"
bool(true)
string(1) "b"
bool(true)

Exemplul de mai sus va afișa în PHP 5.4:

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)

Notă:

Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or {} silently returns NULL.

Notă:

PHP 5.5 added support for accessing characters within string literals using [] or {}.

Useful functions and operators

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 regular expression functions or the Perl-compatible regular expression functions for advanced find & replace functionality.

There are also functions for URL strings, and functions to encrypt/decrypt strings (mcrypt and mhash).

Finally, see also the character type functions.

Converting to string

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 boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

An integer 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).

Notă:

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.

Objects in PHP 4 are always converted to the string "Object". To print the values of object properties for debugging reasons, read the paragraphs below. To get an object's class name, use the get_class() function. As of PHP 5, the __toString method is used when applicable.

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. If the PHP engine was built with WDDX support, PHP values can also be serialized as well-formed XML text.

String conversion to numbers

When a string is evaluated in a numeric context, the resulting value and type are determined as follows.

If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

<?php
$foo 
"10.5";                // $foo is float (11.5)
$foo "-1.3e3";              // $foo is float (-1299)
$foo "bob-1.3e3";           // $foo is integer (1)
$foo "bob3";                // $foo is integer (1)
$foo "10 Small Pigs";       // $foo is integer (11)
$foo "10.2 Little Piggies"// $foo is float (14.2)
$foo "10.0 pigs " 1;          // $foo is float (11)
$foo "10.0 pigs " 1.0;        // $foo is float (11)     
?>

For more information on this conversion, see the Unix manual page for strtod(3).

To test any of the examples in this section, cut and paste the examples and insert the following line to see what's going on:

<?php
echo "\$foo==$foo; type is " gettype ($foo) . "<br />\n";
?>

Do not expect to get the code of one character by converting it to integer, as is done in C. Use the ord() and chr() functions to convert between ASCII codes and characters.

Details of the String Type

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

  • 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, substr(), strpos(), strlen() or strcmp(). Another way to think of these functions is that operate on memory buffers, i.e., they work with bytes and byte offsets.
  • 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 htmlentities() and the majority of the functions in the mbstring extension.
  • Others use the current locale (see setlocale()), but operate byte-by-byte. This is the case of strcasecmp(), strtoupper() and ucfirst(). This means they can be used only with single-byte encodings, as long as the encoding is matched by the locale. For instance strtoupper("á") may return "Á" if the locale is correctly set and á is encoded with a single byte. If it is encoded in UTF-8, the correct result will not be returned and the resulting string may or may not be returned corrupted, depending on the current locale.
  • Finally, they may just assume the string is using a specific encoding, usually UTF-8. This is the case of most functions in the intl extension and in the PCRE extension (in the last case, only when the u modifier is used). Although this is due to their special purpose, the function utf8_decode() assumes a UTF-8 encoding and the function utf8_encode() assumes an ISO-8859-1 encoding.

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.

add a note add a note

User Contributed Notes 40 notes

up
41
gtisza at gmail dot com
2 years ago
The documentation does not mention, but a closing semicolon at the end of the heredoc is actually interpreted as a real semicolon, and as such, sometimes leads to syntax errors.

This works:

<?php
$foo
= <<<END
abcd
END;
?>

This does not:

<?php
foo
(<<<END
abcd
END;
);
// syntax error, unexpected ';'
?>

Without semicolon, it works fine:

<?php
foo
(<<<END
abcd
END
);
?>
up
3
necrodust44 at gmail dot com
7 months ago
String conversion to numbers.

Unfortunately, the documentation is not correct.

«The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).»

It is not said and is not shown in examples throughout the documentation that, while converting strings to numbers, leading space characters are ignored, like with the strtod function.

<?php
   
echo "     \v\f    \r   1234" + 1;    // 1235
   
var_export ("\v\f    \r   1234" == "1234");    // true
?>

However, PHP's behaviour differs even from the strtod's. The documentation says that if the string contains a "e" or "E" character, it will be parsed as a float, and suggests to see the manual for strtod for more information. The manual says

«A hexadecimal number consists of a "0x" or "0X" followed by a nonempty sequence of hexadecimal digits possibly containing a radix character, optionally followed by a binary exponent.  A binary exponent consists of a 'P' or 'p', followed by an optional plus or minus sign, followed by a nonempty sequence of decimal digits, and indicates multiplication by a power of 2.»

But it seems that PHP does not recognise the exponent or the radix character.

<?php
   
echo "0xEp4" + 1;     // 15
?>

strtod also uses the current locale to choose the radix character, but PHP ignores the locale, and the radix character is always 2E. However, PHP uses the locale while converting numbers to strings.

With strtod, the current locale is also used to choose the space characters, I don't know about PHP.
up
13
chAlx at findme dot if dot u dot need
6 years ago
To save Your mind don't read previous comments about dates  ;)

When both strings can be converted to the numerics (in ("$a" > "$b") test) then resulted numerics are used, else FULL strings are compared char-by-char:

<?php
var_dump
('1.22' > '01.23'); // bool(false)
var_dump('1.22.00' > '01.23.00'); // bool(true)
var_dump('1-22-00' > '01-23-00'); // bool(true)
var_dump((float)'1.22.00' > (float)'01.23.00'); // bool(false)
?>
up
13
atnak at chejz dot com
10 years ago
Here is a possible gotcha related to oddness involved with accessing strings by character past the end of the string:

$string = 'a';

var_dump($string[2]);  // string(0) ""
var_dump($string[7]);  // string(0) ""
$string[7] === '';  // TRUE

It appears that anything past the end of the string gives an empty string..  However, when E_NOTICE is on, the above examples will throw the message:

Notice:  Uninitialized string offset:  N in FILE on line LINE

This message cannot be specifically masked with @$string[7], as is possible when $string itself is unset.

isset($string[7]);  // FALSE
$string[7] === NULL;  // FALSE

Even though it seems like a not-NULL value of type string, it is still considered unset.
up
9
dee jay simple 0 0 7 at ge mahl dot com
3 years ago
I recently discovered the joys of using heredoc with sprintf and positions. Useful if you want some code to iterate, you can repeat placeholders.

<?php

function getNumber($num = 0) {
   
$foo = rand(1,20);
    return (
$foo + $num);
}
function
getString() {
   
$foo = array("California","Oregon","Washington");
   
shuffle($foo);
    return
$foo[0];
}
function
getDiv() {
   
$num = getNumber();
   
$div = sprintf( "<div>%s</div>", getNumber(rand(-5,5)) );
    return
$div;
}
$string = <<<THESTRING
I like the state of %1\$s <br />
I picked: %2\$d as a number, <br />
I also picked %2\$d as a number again <br />
%3\$s<br />
%3\$s<br />
%3\$s<br />
%3\$s<br />
%3\$s<br />
THESTRING;

$returnText = sprintf$string, getString(),getNumber(),getDiv()  );

echo
$returnText;

?>

Expected output of the above code:

I like the state of Oregon
I picked: 15 as a number,
I also picked 15 as a number again
5

5

5

5

5
up
7
php at richardneill dot org
1 year ago
Leading zeroes in strings are (least-surprise) not treated as octal.
Consider:
  $x = "0123"  + 0;  
  $y = 0123 + 0;
  echo "x is $x, y is $y";    //prints  "x is 123, y is 83"
in other words:
* leading zeros in numeric literals in the source-code are interpreted as "octal", c.f. strtol().
* leading zeros in strings (eg user-submitted data), when cast (implicitly or explicitly) to integer are ignored, and considered as decimal, c.f. strtod().
up
6
deminy at deminy dot net
5 years ago
Although current documentation says 'A string literal can be specified in four different ways: ...', actually there is a fifth way to specify a (binary) string:

<?php $binary = b'This is a binary string'; ?>

The above statement declares a binary string using the 'b' prefix, which is available since PHP 5.2.1. However, it will only have effect as of PHP 6.0.0, as noted on http://www.php.net/manual/en/function.is-binary.php .
up
5
og at gams dot at
7 years ago
easy transparent solution for using constants in the heredoc format:
DEFINE('TEST','TEST STRING');

$const = get_defined_constants();

echo <<<END
{$const['TEST']}
END;

Result:
TEST STRING
up
3
m021 at springtimesoftware dot com
2 years ago
Heredoc literals delete any trailing space (tabs and blanks) on each line. This is unexpected, since quoted strings do not do this. This is probably done for historical reasons, so would not be considered a bug.
up
3
lelon at lelon dot net
9 years ago
You can use the complex syntax to put the value of both object properties AND object methods inside a string.  For example...
<?php
class Test {
    public
$one = 1;
    public function
two() {
        return
2;
    }
}
$test = new Test();
echo
"foo {$test->one} bar {$test->two()}";
?>
Will output "foo 1 bar 2".

However, you cannot do this for all values in your namespace.  Class constants and static properties/methods will not work because the complex syntax looks for the '$'.
<?php
class Test {
    const
ONE = 1;
}
echo
"foo {Test::ONE} bar";
?>
This will output "foo {Test::one} bar".  Constants and static properties require you to break up the string.
up
1
headden at karelia dot ru
5 years ago
Here is an easy hack to allow double-quoted strings and heredocs to contain arbitrary expressions in curly braces syntax, including constants and other function calls:

<?php

// Hack declaration
function _expr($v) { return $v; }
$_expr = '_expr';

// Our playground
define('qwe', 'asd');
define('zxc', 5);

$a=3;
$b=4;

function
c($a, $b) { return $a+$b; }

// Usage
echo "pre {$_expr(1+2)} post\n"; // outputs 'pre 3 post'
echo "pre {$_expr(qwe)} post\n"; // outputs 'pre asd post'
echo "pre {$_expr(c($a, $b)+zxc*2)} post\n"; // outputs 'pre 17 post'

// General syntax is {$_expr(...)}
?>
up
-2
Ray.Paseur often uses Gmail
7 months ago
In Example #8, above, consider the risk to the script if a programmer were to define('koolaid1', 'XYZ');  For this reason it's wise to use quotes around literal-string associative array keys.  As written without quotes, PHP should raise a Notice.
up
0
harmor
6 years ago
So you want to get the last character of a string using "String access and modification by character"?  Well negative indexes are not allowed so $str[-1] will return an empty string.

<?php
//Tested using: PHP 5.2.5

$str = 'This is a test.';

$last = $str[-1];                  //string(0) ""
$realLast = $str[strlen($str)-1];  //string(1) "."
$substr = substr($str,-1);         //string(1) "."

echo '<pre>';
var_dump($last);
var_dump($realLast);
var_dump($substr);
up
0
rkfranklin+php at gmail dot com
7 years ago
If you want to use a variable in an array index within a double quoted string you have to realize that when you put the curly braces around the array, everything inside the curly braces gets evaluated as if it were outside a string.  Here are some examples:

<?php
$i
= 0;
$myArray[Person0] = Bob;
$myArray[Person1] = George;

// prints Bob (the ++ is used to emphasize that the expression inside the {} is really being evaluated.)
echo "{$myArray['Person'.$i++]}<br>";

// these print George
echo "{$myArray['Person'.$i]}<br>";
echo
"{$myArray["Person{$i}"]}<br>";

// These don't work
echo "{$myArray['Person$i']}<br>";
echo
"{$myArray['Person'$i]}<br>";

// These both throw fatal errors
// echo "$myArray[Person$i]<br>";
//echo "$myArray[Person{$i}]<br>";
?>
up
0
bishop
8 years ago
You may use heredoc syntax to comment out large blocks of code, as follows:
<?php
<<<_EOC
    // end-of-line comment will be masked... so will regular PHP:
    echo (
$test == 'foo' ? 'bar' : 'baz');
    /* c-style comment will be masked, as will other heredocs (not using the same marker) */
    echo <<<EOHTML
This is text you'll never see!       
EOHTML;
    function defintion(
$params) {
        echo 'foo';
    }
    class definition extends nothing     {
       function definition(
$param) {
          echo 'do nothing';
       }      
    }

    how about syntax errors?; = gone, I bet.
_EOC;
?>

Useful for debugging when C-style just won't do.  Also useful if you wish to embed Perl-like Plain Old Documentation; extraction between POD markers is left as an exercise for the reader.

Note there is a performance penalty for this method, as PHP must still parse and variable substitute the string.
up
0
webmaster at rephunter dot net
8 years ago
Use caution when you need white space at the end of a heredoc. Not only is the mandatory final newline before the terminating symbol stripped, but an immediately preceding newline or space character is also stripped.

For example, in the following, the final space character (indicated by \s -- that is, the "\s" is not literally in the text, but is only used to indicate the space character) is stripped:

$string = <<<EOT
this is a string with a terminating space\s
EOT;

In the following, there will only be a single newline at the end of the string, even though two are shown in the text:

$string = <<<EOT
this is a string that must be
followed by a single newline

EOT;
up
-1
cvolny at gmail dot com
5 years ago
I commented on a php bug feature request for a string expansion function and figured I should post somewhere it might be useful:

using regex, pretty straightforward:
<?php
function stringExpand($subject, array $vars) {
   
// loop over $vars map
   
foreach ($vars as $name => $value) {
       
// use preg_replace to match ${`$name`} or $`$name`
       
$subject = preg_replace(sprintf('/\$\{?%s\}?/', $name), $value,
$subject);
    }
   
// return variable expanded string
   
return $subject;
}
?>

using eval() and not limiting access to only certain variables (entire current symbol table including [super]globals):

<?php
function stringExpandDangerous($subject, array $vars = array(), $random = true) {
   
       
// extract $vars into current symbol table
       
extract($vars);
       
       
$delim;
       
// if requested to be random (default), generate delim, otherwise use predefined (trivially faster)
       
if ($random)
           
$delim = '___' . chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . '___';
        else
           
$delim = '__ASDFZXCV1324ZXCV__'// button mashing...
       
        // built the eval code
       
$statement = "return <<<$delim\n\n" . $subject . "\n$delim;\n";
       
       
// execute statement, saving output to $result variable
       
$result = eval($statement);
       
       
// if eval() returned FALSE, throw a custom exception
       
if ($result === false)
            throw new
EvalException($statement);
       
       
// return variable expanded string
       
return $result;
    }
?>

I hope that helps someone, but I do caution against using the eval() route even if it is tempting.  I don't know if there's ever a truely safe way to use eval() on the web, I'd rather not use it.
up
-1
shd at earthling dot net
5 years ago
If you want a parsed variable surrounded by curly braces, just double the curly braces:

<?php
  $foo
= "bar";
  echo
"{{$foo}}";
?>

will just show {bar}. The { is special only if followed by the $ sign and matches one }. In this case, that applies only to the inner braces. The outer ones are not escaped and pass through directly.
up
-2
Richard Neill
7 years ago
Unlike bash, we can't do
  echo "\a"       #beep!

Of course, that would be rather meaningless for PHP/web, but it's useful for PHP-CLI. The solution is simple:  echo "\x07"
up
-2
bryant at zionprogramming dot com
7 years ago
As of (at least) PHP 5.2, you can no longer convert an object to a string unless it has a __toString method. Converting an object without this method now gives the error:

PHP Catchable fatal error:  Object of class <classname> could not be converted to string in <file> on line <line>

Try this code to get the same results as before:

<?php

if (!is_object($value) || method_exists($value, '__toString')) {
   
$string = (string)$value;
} else {
   
$string = 'Object';
}

?>
up
-3
steve at mrclay dot org
6 years ago
Simple function to create human-readably escaped double-quoted strings for use in source code or when debugging strings with newlines/tabs/etc.

<?php
function doubleQuote($str) {
   
$ret = '"';
    for (
$i = 0, $l = strlen($str); $i < $l; ++$i) {
       
$o = ord($str[$i]);
        if (
$o < 31 || $o > 126) {
            switch (
$o) {
                case
9: $ret .= '\t'; break;
                case
10: $ret .= '\n'; break;
                case
11: $ret .= '\v'; break;
                case
12: $ret .= '\f'; break;
                case
13: $ret .= '\r'; break;
                default:
$ret .= '\x' . str_pad(dechex($o), 2, '0', STR_PAD_LEFT);
            }
        } else {
            switch (
$o) {
                case
36: $ret .= '\$'; break;
                case
34: $ret .= '\"'; break;
                case
92: $ret .= '\\\\'; break;
                default:
$ret .= $str[$i];
            }
        }
    }
    return
$ret . '"';
}
?>
up
-3
Liesbeth
5 years ago
If you need to emulate a nowdoc in PHP < 5.3, try using HTML mode and output capturing. This way '$' or '\n' in your string won't be a problem anymore (but unfortunately, '<?' will be).

<?php

// Start of script

ob_start(); ?>
  A text with 'quotes'
    and $$$dollars$$$.
<?php $input = ob_get_contents(); ob_end_clean();

// Do what you want with $input
echo "<pre>" . $input . "</pre>";

?>
up
-4
Michael
3 years ago
Just want to mention that if you want a literal { around a variable within a string, for example if you want your output to be something like the following:

{hello, world}

and all that you put inside the {} is a variable, you can do a double {{}}, like this:

$test = 'hello, world';
echo "{{$test}}";
up
-3
DELETETHIS dot php at dfackrell dot mailshell dot com
8 years ago
Just some quick observations on variable interpolation:

Because PHP looks for {? to start a complex variable expression in a double-quoted string, you can call object methods, but not class methods or unbound functions.

This works:

<?php
class a {
    function
b() {
        return
"World";
    }
}
$c = new a;
echo
"Hello {$c->b()}.\n"
?>

While this does not:

<?php
function b() {
    return
"World";
}
echo
"Hello {b()}\n";
?>

Also, it appears that you can almost without limitation perform other processing within the argument list, but not outside it.  For example:

<?
$true = true;
define("HW", "Hello World");
echo "{$true && HW}";
?>

gives: Parse error: parse error, unexpected T_BOOLEAN_AND, expecting '}' in - on line 3

There may still be some way to kludge the syntax to allow constants and unbound function calls inside a double-quoted string, but it isn't readily apparent to me at the moment, and I'm not sure I'd prefer the workaround over breaking out of the string at this point.
up
-5
Evan K
6 years ago
I encountered the odd situation of having a string containing unexpanded escape sequences that I wanted to expand, but also contained dollar signs that would be interpolated as variables.  "$5.25\n", for example, where I want to convert \n to a newline, but don't want attempted interpolation of $5.

Some muddling through docs and many obscenties later, I produced the following, which expands escape sequences in an existing string with NO interpolation.

<?php

// where we do all our magic
function expand_escape($string) {
    return
preg_replace_callback(
       
'/\\\([nrtvf]|[0-7]{1,3}|[0-9A-Fa-f]{1,2})?/',
       
create_function(
           
'$matches',
           
'return ($matches[0] == "\\\\") ? "" : eval( sprintf(\'return "%s";\', $matches[0]) );'
       
),
       
$string
   
);
}

// a string to test, and show the before and after
$before = 'Quantity:\t500\nPrice:\t$5.25 each';
$after = expand_escape($before);
var_dump($before, $after);

/* Outputs:
string(34) "Quantity:\t500\nPrice:\t$5.25 each"
string(31) "Quantity:    500
Price:    $5.25 each"
*/

?>
up
-5
saamde at gmail dot com
4 years ago
Watch out for the "unexpected T_SL" error.  This appears to occur when there is white space just after "<<<EOT" and since it's white space it's real hard to spot the error in your code.
up
-5
Denis R.
2 years ago
Hi.

I noticed that the documentation does not mention that when you have an XML element which contains a dash (-) in its name can only be accessed using the bracelets notation.
For example:
<xml version="1">
<root>
   <element-one>value4element-one</element-one>
</root>

to access the above 'element-one' using SimpleXML you need to use the following:

$simpleXMLObj->root->{'element-one'}

to retrieve the value.

Hope this helps,
Denis R.
up
-6
mcamiano at ncsu dot edu
2 years ago
Regarding the lack of complex expression interpolation, just assign an identity function to a variable and call it:

function id($arg) { return $arg; }

$expr = id;

echo "Field is: {$expr( "1 ". ucfirst('whatzit')) }";

It is slower due to an additional function call, but it does avoid the assignment of a one-shot temporary variable. When there are a lot of very simple value transformations made just for display purposes, it can de-clutter code.
up
-4
www.feisar.de
10 years ago
watch out when comparing strings that are numbers. this example:

<?php

$x1
= '111111111111111111';
$x2 = '111111111111111112';

echo (
$x1 == $x2) ? "true\n" : "false\n";

?>

will output "true", although the strings are different. With large integer-strings, it seems that PHP compares only the integer values, not the strings. Even strval() will not work here.

To be on the safe side, use:

$x1 === $x2
up
-7
&#34;Sascha Ziemann&#34;
4 years ago
Empty strings seem to be no real strings, because they behave different to strings containing data. Here is an example.

It is possible to change a character at a specific position using the square bracket notation:
<?php
$str
= '0';
$str[0] = 'a';
echo
$str."\n"; // => 'a'
?>

It is also possible to change a character with does not exist, if the index is "behind" the end of the string:
<?php
$str
= '0';
$str[1] = 'a';
echo
$str."\n"; // => 0a
?>

But if you do that on an empty string, the string gets silently converted into an array:
<?php
$str
= '';
$str[0] = 'a';
echo
$str."\n"; // => Array
?>
up
-6
Jonathan Lozinski
10 years ago
A note on the heredoc stuff.

If you're editing with VI/VIM and possible other syntax highlighting editors, then using certain words is the way forward.  if you use <<<HTML for example, then the text will be hightlighted for HTML!!

I just found this out and used sed to alter all EOF to HTML.

JAVASCRIPT also works, and possibly others.  The only thing about <<<JAVASCRIPT is that you can't add the <script> tags..,  so use HTML instead, which will correctly highlight all JavaScript too..

You can also use EOHTML, EOSQL, and EOJAVASCRIPT.
up
-8
sgbeal at googlemail dot com
3 years ago
The docs say: "Heredoc text behaves just like a double-quoted string, without the double quotes" but there is a notable hidden exception to that rule: the final newline in the string (the one before closing heredoc token) is elided. i.e. if you have:

$foo = <<<EOF
a
b
c
EOF;

the result is equivalent to "a\nb\nc", NOT "a\nb\nc\n" like the docs imply.
up
-10
Obeliks
5 years ago
Expectedly <?php $string[$x] ?> and <?php substr($string, $x, 1) ?> will yield the same result... normally!

However, when you turn on the  Function Overloading Feature (http://php.net/manual/en/mbstring.overload.php), this might not be true!

If you use this Overloading Feature with 3rd party software, you should check for usage of the String access operator, otherwise you might be in for some nasty surprises.
up
-6
Anonymous
6 months ago
$my_int = "12,140";
echo  1 + $my_int ;

Returns 13 not the expected 12141
up
-11
fmouse at fmp dot com
7 years ago
It may be obvious to some, but it's convenient to note that variables _will_ be expanded inside of single quotes if these occur inside of a double-quoted string.  This can be handy in constructing exec calls with complex data to be passed to other programs.  e.g.:

$foo = "green";
echo "the grass is $foo";
the grass is green

echo 'the grass is $foo';
the grass is $foo

echo "the grass is '$foo'";
the grass is 'green'
up
-17
Ultimater at gmail dot com
3 years ago
If you require a NowDoc but don't have support for them on your server -- since your PHP version is less than PHP 5.3.0 -- and you are in need of a workaround, I'd suggest using PHP's __halt_compiler() which is basically a knock-off of Perl's __DATA__ token if you are familiar with it.

Give this a run to see my suggestion in action:

<?php
//set $nowDoc to a string containing a code snippet for the user to read
$nowDoc = file_get_contents(__FILE__,null,null,__COMPILER_HALT_OFFSET__);
$nowDoc=highlight_string($nowDoc,true);

echo <<<EOF
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>NowDoc support for PHP &lt; 5.3.0</title>
<meta name="author" content="Ultimater at gmail dot com" />
<meta name="about-this-page"
content="Note that I built this code explicitly for the
php.net documenation for demonstrative purposes." />
<style type="text/css">
body{text-align:center;}
table.border{background:#e0eaee;margin:1px auto;padding:1px;}
table.border td{padding:5px;border:1px solid #8880ff;text-align:left;
background-color:#eee;}
code ::selection{background:#5f5color:white;}
code ::-moz-selection{background:#5f5;color:white;}
a{color:#33a;text-decoration:none;}
a:hover{color:rgb(3,128,252);}
</style>
</head>
<body>
<h1 style="margin:1px auto;">
<a
href="http://php.net/manual/en/language.types.string.php#example-77">
Example #8 Simple syntax example
</a></h1>
<table class="border"><tr><td>
$nowDoc
</td></tr></table></body></html>
EOF;

__halt_compiler()
//Example code snippet we want displayed on the webpage
//note that the compiler isn't actually stopped until the semicolon
;<?php
$juices
= array("apple", "orange", "koolaid1" => "purple");

echo
"He drank some $juices[0] juice.".PHP_EOL;
echo
"He drank some $juices[1] juice.".PHP_EOL;
echo
"He drank some juice made of $juice[0]s.".PHP_EOL; // Won't work
echo "He drank some $juices[koolaid1] juice.".PHP_EOL;

class
people {
    public
$john = "John Smith";
    public
$jane = "Jane Smith";
    public
$robert = "Robert Paulsen";
   
    public
$smith = "Smith";
}

$people = new people();

echo
"$people->john drank some $juices[0] juice.".PHP_EOL;
echo
"$people->john then said hello to $people->jane.".PHP_EOL;
echo
"$people->john's wife greeted $people->robert.".PHP_EOL;
echo
"$people->robert greeted the two $people->smiths."; // Won't work
?>
up
-15
penda ekoka
7 years ago
error control operator (@) with heredoc syntax:

the error control operator is pretty handy for supressing minimal errors or omissions. For example an email form that request some basic non mandatory information to your users. Some may complete the form, other may not. Lets say you don't want to tweak PHP for error levels and you just wish to create some basic template that will be emailed to the admin with the user information submitted. You manage to collect the user input in an array called $form:

<?php
// creating your mailer
$mailer = new SomeMailerLib();
$mailer->from = ' System <mail@yourwebsite.com>';
$mailer->to = 'admin@yourwebsite.com';
$mailer->subject = 'New user request';
// you put the error control operator before the heredoc operator to suppress notices and warnings about unset indices like this
$mailer->body = @<<<FORM
Firstname = {$form['firstname']}
Lastname =
{$form['lastname']}
Email =
{$form['email']}
Telephone =
{$form['telephone']}
Address =
{$form['address']}
FORM;

?>
up
-4
espertalhao04 at hotmail dot com
10 months ago
gtisza at gmail dot com

You incorrectly stated that thee documentation doesn't refer anything about the semicolon at the end of the heredocs and nowdocs  being interpreted as a "real" semicolon.

If you read carefully, you will notice this, in the 1st sentence of the warning about heredocs:

"It is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (;)."

Interesting...
It is refering about semicolons...

But wait, there is more:

http://php.net/manual/en/language.basic-syntax.instruction-separation.php
1st sentence says:
"As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement."

So, here says that semicolons are statement separators, basicly...

So, if you put a "real" semicolon at the end of these examples:
<?php
    $a
=5;
   
$foo="String";
   
$bar=array();
   
$yep=null;
   
$other=func();
?>
Why shouldn't you put at the end of heredocs and nowdocs?
After all, a heredoc or a nowdoc is simply a string.

You should read more carefully the documentation first before saying any comment.

About serious questions:
I didn't read all comments here, but you can run functions inside strings and heredocs.

And you can even nest them inside {}

Example:
<?php
    $f
=function($x){$a=func_get_args();unset($a[0]);return call_user_func_array($x,$a);};
   
$d=0;
    echo
$b=<<<NUMBERS
4.0909 rounded is: {$f('round',4.0909,$d)}
Time now is:
{$f('time')}
Nested heredocs/nowdocs:
{$f('sprintf',<<<OTHER
Here is an %s of nested %s
OTHER
,
"Example",<<<'NOW'
heredocs and nowdocs
NOW
)}

NUMBERS;

/*echoes (time is system and real time relative):
4.0909 rounded is: 4
Time now is: 1386670912
Nested heredocs/nowdocs: Here is an Example of nested heredocs and nowdocs
*/
?>

It's not pretty, and is hard to read, but sometimes it is useful to confuse curious people (like minifying the code).

Warning: if any function that runs inside a string or heredoc gives a fatal error, the script MAY continue!
up
-30
Salil Kothadia
6 years ago
An interesting finding about Heredoc "syntax error, unexpected $end".
I got this error because I did not use the php close tag "?>" and I had no code after the heredoc code.

foo1.php code gives "syntax error, unexpected $end".
But in foo2.php and foo3.php, when you add a php close tag or when you have some more code after heredoc it works fine.

Example Code:
foo1.php
1. <?php
2. $str
= <<<EOD
3. Example of string
4. spanning multiple lines
5. using heredoc syntax.
6. EOD;
7.

foo2.php
1. <?php
2.
$str = <<<EOD
3. Example of string
4. spanning multiple lines
5. using heredoc syntax.
6. EOD;
7.
8. echo
$str;
9.

foo3.php
1. <?php
2.
$str = <<<EOD
3. Example of string
4. spanning multiple lines
5. using heredoc syntax.
6. EOD;
7. ?>
up
-12
benl39 at free dot fr
7 months ago
Note that :

<?php
echo 'error' == 0, '<br>'; // TRUE
echo 'error' == '0', '<br>'; // FALSE
echo '0' == 0, '<br>'; // TRUE

// So, 'error' != 'error' ?
?>
To Top