PHP Strings Manual
PHP Strings Manual
Downloads
Documentation
Get Involved
Help
Getting Started
Introduction
A simple tutorial
Language Reference
Basic syntax
Types
Variables
Constants
Expressions
Operators
Control Structures
Functions
Classes and Objects
Namespaces
Errors
Exceptions
Generators
References Explained
Predefined Variables
Predefined Exceptions
Predefined Interfaces and Classes
Context options and parameters
Supported Protocols and Wrappers
Security
Introduction
General considerations
Installed as CGI binary
Installed as an Apache module
Session Security
Filesystem Security
Database Security
Error Reporting
Using Register Globals
User Submitted Data
Magic Quotes
Hiding PHP
Keeping Current
Features
HTTP authentication with PHP
Cookies
Sessions
Dealing with XForms
Handling file uploads
Using remote files
Connection handling
Persistent Database Connections
Safe Mode
Command line usage
Garbage Collection
DTrace Dynamic Tracing
Function Reference
Affecting PHP's Behaviour
1 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
Keyboard Shortcuts
?
This help
j
Next menu item
k
Previous menu item
gp
Previous man page
gn
Next man page
G
Scroll to bottom
gg
Scroll to top
gh
Goto homepage
gs
Goto search
(current page)
/
Focus search box
Arrays
Floating point numbers
PHP Manual
Language Reference
Types
Change language:
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
2 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
hence does not offer native Unicode support. See details of the string type.
Note: As of PHP 7.0.0, there are no particular restrictions regarding the length of a string on 64-bit builds. On 32-bit
builds and in earlier versions, a string can be as large as up to 2GB (2147483647 bytes maximum)
Syntax
single quoted
double quoted
heredoc syntax
nowdoc syntax (since PHP 5.3.0)
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.
Note: 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';
Double quoted
If the string is enclosed in double-quotes ("), PHP will interpret the following 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.4)
\f form feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
\\ backslash
\$ dollar sign
3 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
Sequence Meaning
\" double-quote
the sequence of characters matching the regular expression is a character in octal notation, which silently overflows
\[0-7]{1,3}
to fit in a byte (e.g. "\400" === "\000")
\x[0-9A-
the sequence of characters matching the regular expression is a character in hexadecimal notation
Fa-f]{1,2}
\u{[0-9A- the sequence of characters matching the regular expression is a Unicode codepoint, which will be output to the
Fa-f]+} string as that codepoint's UTF-8 representation (added in PHP 7.0.0)
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.
Warning
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.
<?php
class foo {
public $bar = <<<EOT
bar
EOT;
}
// Identifier must not be indented
?>
<?php
class foo {
public $bar = <<<EOT
bar
EOT;
}
?>
Heredocs can not be used for initializing class properties. Since PHP 5.3, this limitation is valid only for heredocs containing
variables.
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.
<?php
$str = <<<EOD
Example of string
4 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
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;
?>
It is also possible to use the Heredoc syntax to pass data to function arguments:
<?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:
<?php
// Static variables
function foo()
{
static $bar = <<<LABEL
Nothing in here...
LABEL;
}
// Class properties/constants
class foo
{
const BAR = <<<FOOBAR
Constant example
FOOBAR;
5 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
FOOBAR;
}
?>
Starting with PHP 5.3.0, the opening Heredoc identifier may optionally be enclosed in double quotes:
<?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.
<?php
$str = <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
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;
?>
<?php
6 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
class foo {
public $bar = <<<'EOT'
bar
EOT;
}
?>
Note:
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";
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.
<?php
$juices = array("apple", "orange", "koolaid1" => "purple");
class people {
public $john = "John Smith";
public $jane = "Jane Smith";
public $robert = "Robert Paulsen";
7 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
<?php
$array = [-3 => 'foo'];
echo "The element at index -3 is $array[-3].", PHP_EOL;
?>
For anything more complex, you should use the complex 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';
// 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
8 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
// Works.
echo "This works: " . $arr['foo'][3];
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()}}";
It is also possible to access class properties using variables within strings using this syntax.
<?php
class foo {
var $bar = 'I am bar.';
}
Note:
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';
}
Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string
9 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
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.
Note: As of PHP 7.1.0, negative string offsets are also supported. These specify the offset from the end of the string.
Formerly, negative offsets emitted E_NOTICE for reading (yielding an empty string) and E_WARNING for writing (leaving
the string untouched).
Note: Strings may also be accessed using braces, as in $str{42}, for the same purpose.
Warning
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. 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.
Warning
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.
Note: As of PHP 7.1.0, applying the empty index operator on a string throws a fatal error. Formerly, the string was
silently converted to an array.
<?php
// Get the first character of a string
$str = 'This is a test.';
$first = $str[0];
?>
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.
<?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']));
?>
10 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
bool(true)
string(1) "b"
bool(true)
string(1) "a"
bool(true)
string(1) "b"
bool(true)
Note:
Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or
{} silently returns NULL.
Note:
PHP 5.5 added support for accessing characters within string literals using [] or {}.
Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. See String
operators for more information.
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).
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).
Note:
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.
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.
11 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
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.
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 = 1 + "10.5"; // $foo is float (11.5)
$foo = 1 + "-1.3e3"; // $foo is float (-1299)
$foo = 1 + "bob-1.3e3"; // $foo is integer (1)
$foo = 1 + "bob3"; // $foo is integer (1)
$foo = 1 + "10 Small Pigs"; // $foo is integer (11)
$foo = 4 + "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.
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 PHPs 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
12 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
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
up
down
45
John
5 months ago
I've been a PHP programmer for a decade, and I've always been using the "single-quoted literal" and "period-
concatenation" method of string creation. But I wanted to answer the performance question once and for all,
using sufficient numbers of iterations and a modern PHP version. For my test, I used:
php -v
PHP 7.0.12 (cli) (built: Oct 14 2016 09:56:59) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
$outstr = "literal$n$data$int$data$float$n";
47218ms (fastest)
$outstr =<<<EOS
literal$n$data$int$data$float$n
EOS;
47992ms (1.64% slower)
* 10 million iterations (test adapted to see which of the two fastest methods were faster at adding a
newline; either the PHP_EOL literal, or the \n string expansion):
13 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
$outstr = "literal$n$data$int$data$float$n";
4653ms (reference for double-quoted without newline)
$outstr = "literal$n$data$int$data$float$n\n";
4899ms (fastest at newlines)
* 100 million iterations (a test intended to see which one of the two ${var} and {$var} double-quote styles
is faster):
$outstr = "literal$n$data$int$data$float$n";
49058ms (1.15% slower)
$outstr = "literal{$n}{$data}{$int}{$data}{$float}{$n}"
49221ms (1.49% slower)
$outstr = "literal${n}${data}${int}${data}${float}${n}"
48500ms (fastest; the differences are small but this held true across multiple runs of the test, and this was
always the fastest variable encapsulation style)
* 1 BILLION iterations (testing a completely literal string with nothing to parse in it):
It blows my mind. The double-quoted strings "which look so $slow since they have to parse everything for \n
backslashes and $dollar signs to do variable expansion", turned out to be the FASTEST string concatenation
method in PHP - PERIOD!
Single-quotes are only faster if your string is completely literal (with nothing to parse in it and nothing
to concatenate), but the margin is very tiny and doesn't matter.
2. Put your variables in "This is a {$variable} notation", because it's the fastest method which still allows
complex expansions like "This {$var['foo']} is {$obj->awesome()}!". You cannot do that with the "${var}"
style.
3. Feel free to use single-quoted strings for TOTALLY literal strings such as array keys/values, variable
values, etc, since they are a TINY bit faster when you want literal non-parsed strings. But I had to do 1
billion iterations to find a 1.55% measurable difference. So the only real reason I'd consider using single-
quoted strings for my literals is for code cleanliness, to make it super clear that the string is literal.
4. If you think another method such as sprintf() or 'this'.$var.'style' is more readable, and you don't care
about maximizing performance, then feel free to use whatever concatenation method you prefer!
up
down
78
gtisza at gmail dot com
5 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:
14 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
<?php
$foo = <<<END
abcd
END;
?>
<?php
foo(<<<END
abcd
END;
);
// syntax error, unexpected ';'
?>
<?php
foo(<<<END
abcd
END
);
?>
up
down
17
garbage at iglou dot eu
11 months ago
You can use string like array of char (like C)
var_dump($a);
// Return string(17) "String array test"
var_dump($a[0]);
// Return string(1) "S"
var_dump((array) $a[0]);
// Return string(17) "S"
- Norihiori
up
down
5
mark at manngo dot net
3 months ago
I though that it would be helpful to add this comment so that the information at least appears on the right
page on the PHP site.
Note that if you intend to use a double-quoted string with an associative key, you may run into the
T_ENCAPSED_AND_WHITESPACE error. Some regard this as one of the less obvious error messages.
<?php
$fruit=array(
'a'=>'apple',
15 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
'b'=>'banana',
// etc
);
<?php
print "This is a $fruit[a]"; // unquote the key
print "This is a ${fruit['a']}"; // Complex Syntax
print "This is a {$fruit['a']}"; // Complex Syntax variation
?>
I have a personal preference for the last variation as it is more natural and closer to what the expression
would be like outside the string.
Its not clear (to me, at least) why PHP misinterprets the single quote inside the expression but I imagine
that it has something to do with the fact quotes are not part of the value string once the string is
already being parsed the quotes just get in the way ?
up
down
3
nospam at nospam dot com
7 months ago
Beware that consistent with "String conversion to numbers":
<?php
// Because one side is a number, the string is incorrectly converted from intstr to int, which then matches
the test number.
// True for all conditionals such as if and switch statements (probably also while loops)!
// This could be a huge security risk when testing/using/saving user input, while expecting and testing for
only an integer.
// It seems the only fix is for 123 to be a string as '123' so no conversion happens.
?>
up
down
14
lelon at lelon dot net
12 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".
16 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
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
down
13
headden at karelia dot ru
7 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;
// 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'
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
17 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
$const = get_defined_constants();
echo <<<END
{$const['TEST']}
END;
Result:
TEST STRING
up
down
8
atnak at chejz dot com
13 years ago
Here is a possible gotcha related to oddness involved with accessing strings by character past the end of the
string:
$string = 'a';
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:
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
down
6
Richard Neill
9 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
down
1
user at grantsearch dot com dot au
11 months ago
A word of caution about taking the use of single and double quotes shown here too literally.
A convention is established early on, referring to double-quotes (") and semicolon (;) for example, so the
18 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
later section about concatenation using the '.' (dot) operator seems to indicate the dot must be enclosed by
single quotes.
<?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
down
0
gbarros at NOSPAM dot yahoo-inc dot com
7 days ago
Almost every editor (even VIM) will break the syntax highlighting on the case where you have two forward
slashes in a string. Which is perfectly valid in php. In fact, you are likely to have tons of that because of
URLs.
<?php
print_r('hello // world<br>');
print_r("hello // world<br>");
$x = <<< ENDSTR
hello // world<br>
ENDSTR;
print_r( $x );
19 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
$html = <<<"EOD"
<b>$comment</b>
EOD;
$html = <<<EOD
<b>$comment</b>
EOD;
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.
20 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
With strtod, the current locale is also used to choose the space characters, I don't know about PHP.
up
down
1
webmaster at rephunter dot net
11 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
down
-1
shd at earthling dot net
7 years ago
up
down
-2
rkfranklin+php at gmail dot com
9 years ago
21 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
up
down
-2
bishop
11 years ago
up
down
-3
Evan K
9 years ago
22 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
up
down
-4
dee jay simple 0 0 7 at ge mahl dot com
6 years ago
23 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
up
down
-5
Denis R.
4 years ago
up
down
-6
cvolny at gmail dot com
8 years ago
24 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
up
down
-7
m021 at springtimesoftware dot com
5 years ago
up
down
-6
harmor
8 years ago
up
down
-8
mcamiano at ncsu dot edu
4 years ago
up
down
-8
25 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
up
down
-5
espertalhao04 at hotmail dot com
3 years ago
26 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
up
down
-10
Michael
5 years ago
up
down
-10
Jonathan Lozinski
12 years ago
up
down
-11
Liesbeth
7 years ago
up
down
27 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
-12
sgbeal at googlemail dot com
5 years ago
up
down
-12
DELETETHIS dot php at dfackrell dot mailshell dot com
11 years ago
up
down
-10
Anonymous
3 years ago
28 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
up
down
-11
www.feisar.de
13 years ago
up
down
-15
"Sascha Ziemann"
7 years ago
up
down
-15
fmouse at fmp dot com
10 years ago
29 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
up
down
-22
Obeliks
8 years ago
up
down
-20
penda ekoka
10 years ago
up
down
-25
Ultimater at gmail dot com
6 years ago
30 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
up
down
-16
31 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
up
down
-15
Ray.Paseur often uses Gmail
3 years ago
up
down
-17
cnbk201 at gmail dot com
2 years ago
up
down
-37
Salil Kothadia
8 years ago
32 de 33 2/5/17 17:30
PHP: Strings - Manual http://us2.php.net/manual/en/language.types.string.php#language.types....
add a note
Types
Introduction
Booleans
Integers
Floating point numbers
Strings
Arrays
Iterables
Objects
Resources
NULL
Callbacks / Callables
Pseudo-types and variables used in this documentation
Type Juggling
33 de 33 2/5/17 17:30