PHP Strings
Introduction
Strings in PHP are sequences of bytes, such as "We hold these truths to be self-evident" or "Once upon a time" or even "111211211." When you read data from a file or output it to a web browser, your data is represented as strings.
PHP strings are binary-safe (i.e., they can contain null bytes) and can grow and shrink on demand. Their size is limited only by the amount of memory that is available to PHP.
Similar in form and behavior to Perl and the Unix shell, strings can be initialized in three ways: with single quotes, with double quotes, and with the "here document" (heredoc) format. With single-quoted strings, the only special characters you need to escape inside a string are the backslash and the single quote itself. This example shows four single-quoted strings:
print 'I have gone to the store. ' ;
print 'I\ 've gone to the store. ' ;
print 'Would you pay $1.75 for 8 ounces of tap water ? ' ;
print 'In double-quoted strings, newline is represented by \n' ;
It prints:
I have gone to the store.
I've gone to the store.
Would you pay $1.75 for 8 ounces of tap water?
In double-quoted strings, newline is represented by \n
Because PHP doesn't check for variable interpolation or almost any escape sequences in single-quoted strings, defining strings this way is straightforward and fast.
Double-quoted strings don't recognize escape single quotes, but they do recognize interpolated variables and the escape sequences shown in Table 1-1.
Double-quoted string escape sequences
Escape Sequences Character
\n Newline (ASCII 10)
\r Carriage return (ASCII 13)
\t Tab (ASCII 9)
\\ Backslash
\$ Dollar sign
\" Double quote
\0 through \777 Octal value
\x0 through \xFF Hex value
Example Double-quoted strings
print "I've gone to the store.";
print "The sauce cost \$10.25.";
$cost = '$10.25';
print "The sauce cost $cost.";
print "The sauce cost \$\061\060.\x32\x35.";
Example prints:
I've gone to the store.
The sauce cost $10.25.
The sauce cost $10.25.
The sauce cost $10.25.
The last line of Example 1-1 prints the price of sauce correctly because the character 1 is ASCII code 49 decimal and 061 octal. Character 0 is ASCII 48 decimal and 060 octal; 2 is ASCII 50 decimal and 32 hex; and 5 hex; and 5 is ASCII 53 decimal and 35 hex.
Heredoc-specified strings recognize all the interpolations and escapes of double-quoted strings, but they don't require double quotes to be escaped. Heredocs start with <<< and a token. That token (with no leading or trailing whitespace), followed by a to end the statement (if necessary), ends the heredoc.
Example . Defining a here document
print <<< END
It's funny when signs say things like:
Original "Root" Beer
"Free" Gift
Shoes cleaned while "you" wait
or have other misquoted words.
END;
Example prints:
It's funny when signs say things like:
Original "Root" Beer
"Free" Gift
Shoes cleaned while "you" wait
or have other misquoted words.
Newlines, spacing, and quotes are all preserved in a heredoc. By convention, the end-of-string identifier is usually all caps, and it is case sensitive.
Example More here documents
print <<< PARSLEY
It's easy to grow fresh:
Parsley
Chives
on your windowsill
PARSLEY ;
print <<< DOGS
If you like pets, yell out:
DOGS AND CATS ARE GREAT!
DOGS ;
Here docs are especially useful for printing out HTML with interpolated variables because you don't have to escape the double quotes that appears in the HTML elements.
Example Printing HTML with a here document
if ($remaining_cards > 0) {
$url = '/deal.php' ;
$text = 'Deal More Cards';
} else {
$url = '/new-game.php';
$text = 'Start a New Game' ;
}
print <<< HTML
There are <b>$remaining_cards</b> left.
<p>
<a href="$url">$text</a>
HTML;
In Example , the semicolon needs to go after the end-of-string delimiter to tell PHP the statement is ended. In some cases, however, you shouldn't use the semicolon. One of these cases is shown in Example which uses a heredoc with the string concatenation operator.
Example Concentration with a here document
$html = <<< END
<div class="$divClass">
<ul class="$ulclass">
<li>
END
. $listItem . '</li></div>' ;
print $html;
Assuming some reasonable values for the $divClass, $ulclass, and $listItem variables,
Example prints:
<div class="class">>
<ul class="class">
<li> The List Item </li></div>
In Example the expression needs to continue on the next line, so you don't use a semicolon. Note also that in order for PHP to recognize the end-of-string delimiter, the. string concatenation operator needs to go on a separate line from the end-of-string delimiter.
Nowdocs are similar to heredocs, but there is no variable interpolation. So, nowdocs are to heredoc as single-quoted strings are to double-quoted strings. They're best when you have a block of non-PHP code, such as JavaScript, that you want to print as part of an HTML page or send to another program.
For example, if you're using jQuery:
$js = <<<'__JS__'
$. ajax ({
'url': '/api/getStock' ,
'data' : {
'ticker' : 'LNKD'
},
' success' : function ( data ) {
$( "#stock-price" ) .html ( "<strong>$" + data + "</strong>" );
}
});
_JS_;
print $js;
Individual bytes in strings can be referenced with square brackets. The first byte in the string is at index 0.
Example Getting an individual byte in a string
$neighbour = 'Hilda' ;
print $neighbour [3] ;
Example prints:
d
NOTES :
Usually, PHP strings are ASCII strings. You must do extra work to handle non-
ASCII data like UTF-8 or other multibyte character encodings.
The preceding output shows what the raw output looks like. If you view it in a web browser, you will see all the sentences on the same line because HTML requires additional markup to insert line breaks.
No comments:
Post a Comment