Learning Objectives – after this chapter you will be able to:
- Explain how PHP stores strings and how large a string can be.
- Write string literals in the four syntaxes: single-quoted, double-quoted, heredoc and nowdoc.
- Use escape sequences and variable parsing (interpolation) in double-quoted strings.
- Apply common string functions such as
strlen(),strpos(),str_replace()andsubstr().
Strings in PHP
A string is a series of characters. In PHP a character is the same as a byte, so there are exactly 256 different characters possible. Text in UTF-8 (for example Hindi: नमस्ते) uses several bytes per character; for such text use the multibyte functions mb_strlen(), mb_substr() and so on. (Older books suggest utf8_encode()/utf8_decode(); these are deprecated since PHP 8.2 – use mb_convert_encoding() instead.)
It is no problem for a string to become very large. PHP imposes no fixed limit on the size of a string; the only limit is the memory available to the script (memory_limit in php.ini).
A string literal can be specified in four different ways:
- single quoted
- double quoted
- heredoc syntax
- nowdoc syntax
Single-Quoted Strings
The simplest way to specify a string is to enclose it in single quotes (').
- To specify a literal single quote, escape it with a backslash:
\'. - To specify a literal backslash, double it:
\\. - All other backslashes are treated literally: escape sequences such as
\ror\nare output as written, without any special meaning. - Variables are not expanded inside single-quoted strings.
<?php echo 'this is a simple string'; echo '<br>'; echo 'You can also have embedded newlines in strings this way as it is okay to do'; echo '<br>'; // Outputs: Arnold once said: "I'll be back" echo 'Arnold once said: "I\'ll be back"'; echo '<br>'; // Outputs: You deleted C:\*.*? echo 'You deleted C:\\*.*?'; echo '<br>'; // Outputs: You deleted C:\*.*? echo 'You deleted C:\*.*?'; echo '<br>'; // Outputs: This will not expand: \n a newline echo 'This will not expand: \n a newline'; echo '<br>'; // Outputs: Variables do not $expand $either echo 'Variables do not $expand $either'; ?>
this is a simple string You can also have embedded newlines in strings this way as it is okay to do Arnold once said: "I'll be back" You deleted C:\*.*? You deleted C:\*.*? This will not expand: \n a newline Variables do not $expand $either
(The newline inside the second string is displayed as a space, because the browser treats line breaks in HTML as white space.)
Double-Quoted Strings
If the string is enclosed in double quotes ("), PHP interprets more escape sequences:
| Sequence | Meaning |
|---|---|
| \n | linefeed (LF, ASCII 10) |
| \r | carriage return (CR, ASCII 13) |
| \t | horizontal tab (HT, ASCII 9) |
| \v | vertical tab (VT, ASCII 11) |
| \e | escape (ESC, ASCII 27) |
| \f | form feed (FF, ASCII 12) |
| \\ | backslash |
| \$ | dollar sign |
| \" | double quote |
| \[0-7]{1,3} | character in octal notation, e.g. \101 is "A" |
| \x[0-9A-Fa-f]{1,2} | character in hexadecimal notation, e.g. \x41 is "A" |
| \u{hex} | Unicode code point as UTF-8, e.g. \u{20B9} is "₹" |
As in single-quoted strings, escaping any other character prints the backslash too. The most important feature of double-quoted strings is that variable names are expanded (variable parsing / interpolation).
<?php
$name = "Asha";
$fruits = ["apple", "mango"];
$user = ["city" => "Bhopal"];
echo "<pre>";
echo "Hello $name!\n";
echo "Tab\tseparated\tvalues\n";
echo "A quote: \" and a dollar: \$name\n";
echo "Octal \101, hex \x41, rupee \u{20B9}\n";
echo "First fruit: $fruits[0]\n";
echo "City: {$user['city']}\n"; // curly syntax for complex expressions
echo "Name in capitals: " . strtoupper($name) . "\n";
echo "</pre>";
?>Hello Asha! Tab separated values A quote: " and a dollar: $name Octal A, hex A, rupee ₹ First fruit: apple City: Bhopal Name in capitals: ASHA
A simple variable such as $name or $fruits[0] can be written directly inside double quotes. For array elements with string keys, object properties or anything more complex, wrap the expression in curly braces: "{$user['city']}", "{$obj->name}".
Heredoc
A third way to delimit strings is the heredoc syntax: <<<. After this operator an identifier is given, then a new line. The string follows, and then the same identifier again to close the quotation.
- The identifier must follow the same naming rules as other labels in PHP: only letters, digits and underscores, not starting with a digit.
- Heredoc text behaves just like a double-quoted string without the double quotes: quotes need not be escaped, escape codes work and variables are expanded.
- Since PHP 7.3 the closing identifier may be indented, and the same amount of indentation is removed from every line of the text. In older versions it had to start in the first column, with nothing but an optional
;after it. - Heredoc can be used to initialise static variables, class properties and constants (with static values).
<?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
<pre>
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
</pre>
EOT;
?>My name is "MyName". I am printing some Foo. Now, I am printing some Bar2. This should print a capital 'A': A
PHP 8 change. Old notes wrote the constructor of class foo as a method also named foo(). Such "PHP 4 style" constructors are no longer constructors in PHP 8; always use __construct() (Chapter 17).
Heredoc is also convenient for passing long text as a function argument, or for building HTML:
<?php
$product = "Laptop";
$price = 45999;
$html = <<<HTML
<div style="border:1px solid #999;padding:6px;width:220px">
<b>$product</b><br>
Price: Rs. {$price}/-
</div>
HTML;
echo $html;
echo "<pre>";
var_dump(array(<<<EOD
foobar!
EOD));
echo "</pre>";
?>Laptop
Price: Rs. 45999/-
array(1) {
[0]=>
string(7) "foobar!"
}Nowdoc
Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is written like a heredoc, but the identifier is enclosed in single quotes, e.g. <<<'EOT', and no parsing is done inside it: variables are not expanded and escape sequences are not interpreted. It is ideal for embedding PHP code or other large blocks of text without escaping.
<?php
$name = 'MyName';
echo <<<'EOT'
<pre>
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
</pre>
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': \x41Nowdoc (available since PHP 5.3) can be used in any static data context, for example to initialise class properties or constants:
<?php
class Notice
{
const TITLE = <<<'EOT'
Office closed on Monday
EOT;
public $body = <<<'EOT'
Fees can be paid online at $site.
EOT;
}
$n = new Notice();
echo Notice::TITLE . "<br>" . $n->body;
?>Office closed on Monday Fees can be paid online at $site.
Frequently Used String Functions
Part II gives the complete list of string functions. The following are used in almost every program:
<?php
$s = " Welcome to PHP Programming ";
$t = trim($s);
echo "trim: '$t'<br>";
echo "strlen: " . strlen($t) . "<br>";
echo "str_word_count: " . str_word_count($t) . "<br>";
echo "strtoupper: " . strtoupper($t) . "<br>";
echo "strtolower: " . strtolower($t) . "<br>";
echo "ucwords: " . ucwords("php and mysqli") . "<br>";
echo "strrev: " . strrev("PHP") . "<br>";
echo "strpos of 'PHP': " . strpos($t, "PHP") . "<br>";
echo "substr(11, 3): " . substr($t, 11, 3) . "<br>";
echo "str_replace: " . str_replace("PHP", "MySQLi", $t) . "<br>";
echo "str_contains (PHP 8): " . (str_contains($t, "come") ? "yes" : "no") . "<br>";
echo "str_pad: " . str_pad("7", 3, "0", STR_PAD_LEFT) . "<br>";
echo "number_format: " . number_format(1234567.891, 2);
?>trim: 'Welcome to PHP Programming' strlen: 26 str_word_count: 4 strtoupper: WELCOME TO PHP PROGRAMMING strtolower: welcome to php programming ucwords: Php And Mysqli strrev: PHP strpos of 'PHP': 11 substr(11, 3): PHP str_replace: Welcome to MySQLi Programming str_contains (PHP 8): yes str_pad: 007 number_format: 1,234,567.89
Key Takeaways
- A PHP string is a sequence of bytes; size is limited only by memory. Use
mb_*functions for UTF-8 text. - Single quotes: only
\'and\\are special; variables are not expanded. - Double quotes: escape sequences and variable interpolation; use
{…}for complex expressions. - Heredoc
<<<IDbehaves like double quotes; nowdoc<<<'ID'like single quotes. - Since PHP 7.3 the heredoc/nowdoc closing identifier may be indented.
strlen,strpos,substr,str_replace,trim,strtoupperandstr_containsare everyday string functions.
Program File
Extract the ZIP into C:\xampp\htdocs. It creates the folder phpbook/ch08 used in the file labels above; open the programs at http://localhost/phpbook/… with Apache (and MySQL, where needed) started in the XAMPP Control Panel.
Question / Answer (15 questions)
MCQ Test : Check Your Understanding (5 questions)
Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.
Bibliography/References
The notes on this page are the author’s own compilation from the e-book PHP: Basics to Advance. Every program was run on Apache with PHP 8 and MariaDB, and the output shown is the real result of that run. The works listed below were consulted and are cited for attribution and further reading. Product names and trademarks belong to their respective owners.
- The PHP Group. (n.d.). PHP Manual – Strings. https://www.php.net/manual/en/language.types.string.php
- The PHP Group. (n.d.). PHP Manual – String Functions. https://www.php.net/manual/en/ref.strings.php
- The PHP Group. (n.d.). PHP Manual – Multibyte String. https://www.php.net/manual/en/book.mbstring.php
- The PHP Group. (n.d.). PHP Manual – Migrating from PHP 7.2.x to PHP 7.3.x (flexible heredoc). https://www.php.net/manual/en/migration73.new-features.php