Hands-on with PHP — Strings

< Home < PHP OutputsPHP Integers coming soon… >

Sequence of Characters

A string appears as a sequence of characters on your screen. Internally, however, it is an array of bytes that collectively represent some information. The information this byte array represents is usually determined by the type of character encoding, such as UTF-8. Run the code in the String as Byte Array code section to peek into the internal representation of the Chinese character , which means love in English, in hexadecimal and binary respectively. Note that a byte has eight binary bits.

<?php
echo "<pre>";
$string = "爱"; // a string
var_dump($string); // string(3) "爱"

// Convert a string into hexadecimal
$hex = bin2hex($string);
var_dump($hex); // string(6) "e788b1"

// Convert hexadecimal into binary
var_dump(base_convert($hex,16,2)); // string(24) "111001111000100010110001"

// Convert hexadecimal back into string 
$bin = hex2bin($hex);
var_dump($bin); // string(3) "爱"

echo "</pre>";
?>

Notice that although the word appears as one character on your screen, it is represented internally as a three-byte array of 11100111, 10001000, and 10110001 in UTF-8 encoding. For English words, on the other hand, each letter is represented by exactly one byte, e.g. A is represented as 01000001 in ASCII encoding.

String Construction

A string literal can be constructed in one of the four ways as follows:

"This is a double-quoted string."
'This is a single-quoted string.'
<<<identifier
Part of the string
Another part of the string
identifier
<<<'identifier'
Part of the string
Another part of the string
identifier

Double-Quoted Strings

In a double-quoted string, e.g. "This is a double-quoted string.", the two double quotes " are being interpreted as the delimiters of the string, if you want to include a literal double quote in that string, you have to escape it with a literal backslash \, e.g. "\"This is a double-quoted string.\"" as shown in Escaped Double-Quote code section.

<?php
echo "\"This is \r a double-quoted string.\"";
/*
"This is a double-quoted string."
*/
?>

Adding a backslash to a double quote is the PHP’s way to tell the interpreter not to treat it as a string delimiter, thus allowing it to escape from its original representation. The \" is an example of an escape sequence.

Escape Sequences

An escape sequence is a sequence of characters that does not represent the meaning as it is expected when used inside a character or string literal, but is interpreted as another character or another meaning that may be difficult or impossible to represent directly.

PHP honours the following escape sequences if they are used inside a double-quoted string:

Escape Sequence Meaning Remark
\n New Line or Line Feed (LF or ASCII 10)
\r Carriage Return (CR or ASCII 13)
\t Horizontal Tab (HT or ASCII 9)
\v Vertical Tab (VT or ASCII 11) Since PHP 5.2.5
\e Escape (ESC or ASCII 27) Since PHP 5.4.4
\f Form Feed (FF or ASCII 12) Since PHP 5.2.5
\\ Backslash
\$ Dollar Sign
\" Double-quote

Escape sequences are not part of HTML, as such they may not be rendered as expected in the browser. To honour the effect of \n, \r, or \t in the browser, they have to be wrapped inside the HTML tags of <pre> and </pre> as shown in the Preformatted Tags code section below:

<?php
echo "<pre>";
echo "First line.\n";
echo "\tSecond line.\r";
echo "\t\tThird line.";
echo "</pre>";
?>

What happens if you comment out the echo "<pre>"; and echo "</pre>"; statements in the code section above? Check it out!

How do you output escape sequence characters literally? The answer is: escape them! Check it out in the Escaping Escape Sequence code section below:

<?php
echo "<pre>";
echo "List of Escape Sequences for use in Double-Quoted String:", PHP_EOL;
echo "Line Feed: \\n", PHP_EOL;
echo "Carriage Return: \\r", PHP_EOL;
echo "Horizontal Tab: \\t", PHP_EOL;
echo "Vertical Tab: \\v", PHP_EOL;
echo "Escape: \\e", PHP_EOL;
echo "Form Feed: \\f", PHP_EOL;
echo "Backslash: \\\\", PHP_EOL;
echo "Dollar Sign: \\\$", PHP_EOL;
echo "Double-quote: \\\"";
/*
List of Escape Sequences for use in Double-Quoted String:
Line Feed: \n
Carriage Return: \r
Horizontal Tab: \t
Vertical Tab: \v
Escape: \e
Form Feed: \f
Backslash: \\
Dollar Sign: \$
Double-quote: \"
*/
echo "</pre>";
?>

PHP_EOL

Have you noticed that each echo statement ended with a PHP_EOL in the Escaping Escape Sequence code section?

PHP_EOL is a PHP constant, available since PHP 5.0.2, that automatically inserts the correct ‘End Of Line’ symbol for the server platform. Previously, we have been using \n to achieve this. The truth is \n only works on Unix and Mac OS X platforms, while Windows DOS uses \r\n to represent a new line. So, to be certain, use PHP_EOL whenever you need to insert a newline as it works on any server platforms.

Variable Parsing

The most useful feature to double quote strings is the fact that variable names can be included in the strings and parsed to the values that they carry on the fly. You cannot do this with single-quoted strings. Check it out in the Variable Parsing code section.

<?php
$first_name = "Peter";
$last_name = "Leow";
echo "Inside double quotes: My full name is $first_name $last_name.<br>";
echo 'Inside single quotes: My full name is $first_name $last_name.';
?>

Double-Quoted Multi-line Strings

A double-quoted string can span multiple lines with indentations that are outputted accordingly in a console or in a browser when it is wrapped inside the HTML tags of <pre> and </pre>.

<?php
echo "<pre>";
$variable = "double quotes";

$html = "<html>
  <body>
    <div>
      <p>\"This text block is constructed with\t $variable.'</p>
    </div>
  </body>
</html>";

echo htmlentities($html);

echo "</pre>";
?>

Note:

`htmlentities()` is a PHP function that converts all HTML reserved characters, such as <, and >, to HTML entities so as to preserve their literal meanings instead of being interpreted as HTML reserved words, e.g. htmlentities("<") converts the character of < to the HTML entity of &lt; which can then be rendered literally as < in the browser.

However, a better alternative to double-quoting multi-line strings is heredoc construct to be discussed later.

Return to String Constructs

Single-Quoted Strings

In a single-quoted string, e.g. 'This is a single-quoted string.', the two single quotes ' are being interpreted as the delimiters of the string, if you want to include a literal single quote in that string, you have to escape it with a literal backslash \, e.g. "\'This is a single-quoted string.\'" as shown in Escaped Single-Quote code section.

<?php
echo '\'This is a single-quoted string.\'';
/*
'This is a single-quoted string.'
*/
?>

Apart from \' and \\, all other escape sequences discussed in double-quoted strings are treated as mere literal characters with no special meaning inside single-quoted strings. Check it out in the Escape Sequences in Single-Quoted String code section:

<?php
echo "<pre>";
echo 'Escape Sequences in Single-Quoted String:', PHP_EOL;
echo 'Line Feed: \n', PHP_EOL;
echo 'Carriage Return: \r', PHP_EOL;
echo 'Horizontal Tab: \t', PHP_EOL;
echo 'Vertical Tab: \v', PHP_EOL;
echo 'Escape: \e', PHP_EOL;
echo 'Form Feed: \f', PHP_EOL;
echo 'Backslash: \\', PHP_EOL;
echo 'Dollar Sign: \$', PHP_EOL;
echo 'Double-quote: \'';
/*
Escape Sequences in Single-Quoted String:
Line Feed: \n
Carriage Return: \r
Horizontal Tab: \t
Vertical Tab: \v
Escape: \e
Form Feed: \f
Backslash: \
Dollar Sign: \$
Double-quote: '
*/
echo "</pre>";
?>

That means \n will not be honoured as newline in single-quoted strings, how to add a newline then? The answer is PHP_EOL.

Unlike double-quoted strings, variables are not parsed in single-quoted strings. You have already seen it in the Variable Parsing code section above.

Single-Quoted Multi-line Strings

A single-quoted string can span multiple lines with indentations that are outputted accordingly in a console or in a browser when it is wrapped inside the HTML tags of <pre> and </pre>.

<?php
echo '<pre>';
$variable = 'single quotes';

$html = '<html>
  <body>
    <div>
      <p>"This text block is constructed with\t $variable.\'</p>
    </div>
  </body>
</html>';

echo htmlentities($html);

echo '</pre>';
?>

However, a better alternative to single-quoting multi-line strings is nowdoc construct to be discussed later.

Return to String Constructs

Heredoc Strings

The close sibling to double-quoted construct is heredoc. A heredoc string starts with the <<< operator, followed by an identifier, a newline, the actual string, a newline, and ends with the same identifier as shown in this format:

<<<identifier
Part of the string
Another part of the string
identifier

Note:

The closing identifier of *heredoc* must occupy one whole line without indentation and must end with a newline with or without a semicolon.

Run the code in the Heredoc code section to discover the characteristics of a heredoc string.

<?php
echo "<pre>";
$variable = "heredoc";

$html = <<<HTML
<html>
  <body>
    <div>
      <p>"This text block is constructed with\t $variable.'</p>
    </div>
  </body>
</html>
HTML;

echo htmlentities($html);

echo "</pre>";
?>

Like double-quoted construct, heredoc honours escape sequences, variable parsing, and formatting such as indentations and newlines for multi-line strings . Unlike double-quoted construct, however, you can use literal double quotes in heredoc strings without having to escape them.

As you can see, heredoc construct is ideal for multi-line strings that require escaping or variable parsing.

Return to String Constructs

Nowdoc Strings

Nowdoc strings are to single-quoted strings as heredoc strings are to double-quoted strings. A nowdoc string is constructed similarly to a heredoc string but differs in that the opening identifier that follows immediately after the <<< is enclosed in single quotes.

<<<'identifier'
Part of the string
Another part of the string
identifier

Note:

The closing identifier of *Nowdoc* must occupy one whole line without indentation and must end with a newline with or without a semicolon.

Run the code in the Nowdoc code section to discover the characteristics of a nowdoc string.

<?php
echo '<pre>';
$variable = "nowdoc";

$html = <<<'HTML'
<html>
  <body>
    <div>
      <p>"This text block is constructed with\t $variable.'</p>
    </div>
  </body>
</html>
HTML;

echo htmlentities($html);

echo '</pre>';
?>

Like single-quoted construct, nowdoc honours formatting such as indentations and newlines for multi-line strings but not escape sequences and variable parsing. Unlike single-quoted construct, however, you can use literal single quotes in nowdoc strings without having to escape them.

As you can see, nowdoc construct is ideal for embedding PHP code or other large blocks of text that require neither escaping nor variable parsing.

Return to String Constructs

Some Useful String Functions

strlen()

integer strlen( string $string )

Example

echo strlen( "Hello World." );

Explanation

A string function that returns the length of the $string argument on success, or zero if it is empty.

Application

<?php
echo strlen("A 19-letter string.");
/*
19
*/
?>

ltrim()

string ltrim( string $string [, string $unwanted_characters ] )

Example

echo ltrim( "Not a good person!?", "Not " );

Explanation

A string function that removes $unwanted_characters existing on the left side of the $string argument and returns the result as a new string. The $unwanted_characters parameter is optional and defaults to " " white space, \0 NULL, \t tab, \n newline, \r carriage return, and \x0B vertical tab, if omitted.

Application

<?php
echo ltrim("Not a good person!?", "Not ");
/*
a good person!?
*/
?>

rtrim()

string rtrim( string $string [, string $unwanted_characters ] )

Example

echo rtrim( "Not a good person!?", "?" );

Explanation

Similar to the ltrim() function, except that rtrim() removes $unwanted_characters existing on the right side of the $string argument and returns the result as a new string.

Application

<?php
echo rtrim("Not a good person!?", "?");
/*
Not a good person!
*/
?>

trim()

string trim( string $string [, string $unwanted_characters ] )

Example

echo trim( "Not a good person!?", "Not? " );

Explanation

trim() function is the amalgamation of ltrim() and rtrim(), it removes $unwanted_characters existing on either side of the $string argument and returns the result as a new string.

Application

<?php
echo trim("Not a good person!?", "Not? ");
/*
a good person!
*/
?>

strtolower()

string strtolower( string $string )

Example

echo strtolower( "ABCDEFGHIJKLMNOP" );

Explanation

A string function that converts all characters in the $string argument to lowercase and returns the result as a new string.

Application

<?php
echo strtolower("ABCDEFGHIJKLMNOP");
/*
abcdefghijklmnop
*/
?>

strtoupper()

string strtoupper( string $string )

Example

echo strtoupper( "abcdefghijklmnop" );

Explanation

A string function that converts all characters in the $string argument to uppercase and returns the result as a new string.

Application

<?php
echo strtoupper("abcdefghijklmnop");
/*
ABCDEFGHIJKLMNOP
*/
?>

Quiz

<?php
echo '<pre>';
echo '\n';
echo '</pre>';
?>
What is the expected output in the browser from executing the PHP script in Listing 1?
\n
Correct!
n
Wrong!
‘\n’
Wrong!
Newline.
Wrong!
<?php
echo '<pre>';
echo "\n";
echo '</pre>';
?>
What is the expected output in the browser from executing the PHP script in Listing 2?
Newline.
Correct!
n
Wrong!
‘\n’
Wrong!
\n
Wrong!
Which of these PHP statements can produce this output? ‘Hello world!’
echo ” ‘Hello world!’ “;
Correct!
echo ‘ \’Hello world!\’ ‘;
Correct!
echo ‘ “Hello world!” ‘;
Wrong!
echo ” \’Hello world!\’ “;
Wrong!
<?php
$gender = "Male";
echo 'The output is $gender.';
?>
What is the expected output from executing the PHP script in Listing 3?
The output is $gender.
Correct!
The output is Male.
Wrong!
The output is $gender = “Male”.
Wrong!
Nothing.
Wrong!
Which one of the following string constructs is the most ideal for multi-line strings that require escaping or variable parsing?
Heredoc
Correct!
Nowdoc
Wrong!
Single-quoted
Wrong!
Double-quoted
Wrong!
Which one of the following string constructs is the most ideal for multi-line strings that require neither escaping nor variable parsing?
Nowdoc
Correct!
Heredoc
Wrong!
Single-quoted
Wrong!
Double-quoted
Wrong!

< Home < PHP OutputsPHP Integers coming soon… >

Tagged with: ,

Speak Your Mind