advertisement
Strings:
A string is an array of characters. This tutorial demonstrates the use of string to manipulate text. A string can be represented in one of the following four ways; single quoted, double quoted, heredoc syntax and nowdoc syntax. Before describing each string in detail, it would be appropriate to discuss about escape sequence. Escape sequence are used to format the output text and other output options. The table below presents the escape sequences for special characters.
Sequence |
Explanation |
\n |
Linefeed |
\r |
Carriage return |
\t |
Horizontal tab |
\v |
Vertical tab |
\f |
Form feed |
\\ |
Backslash |
\$ |
Dollar sign |
\” |
Double quote |
There are many functions available in PHP to manipulate strings. For a complete list of reference on functions please visit the link http://www.w3schools.com/PHP/php_ref_string.asp
Single quoted
A string can be represented in single quote. In PHP a single quote string can be expanded in more than one line. Remember that, if we attempt to escape the character other than the above table, it will print the backslash too.
Example#1
5 | $myString = 'Hello World' ; |
12 | $myString = '"Hello World"' ; |
17 | $myString = '"Hello World, let\'s begin with more complex examples"' ; |
Double quoted
PHP recognized all of the above escape sequences if it is enclosed in double quotes. Remember that, as in single quoted string, if we attempt to escape the character other than the above table, it will print the backslash too.
Example #2
6 | $myString = "Hello World" ; |
14 | $myString = "Hello World \n This will be printed in a new line" ; |
23 | echo 'The value of $x is ' . "$x" . ' and value of $y is ' . "$20" . '. The result of $x + $y is ' . "30" ; |
heredoc
heredoc syntax <<< can also be used to represent string. heredoc text behaves like double quote string, except that it is not enclosed with double quote, that means that escape sequence can be used in heredoc in the similar manner. The variables are also expanded in heredoc text.
Example#3
9 | This is your heredoc example, |
10 | and this can be expanded as necessary |
nowdoc
heredoc text behaves like double quote string while nowdoc text behaves like single quote string. The main difference is that escape sequence cannot be used in nowdoc.
Example#4
8 | This is your nowdoc example, |
9 | and this can be expanded as necessary |