PHP String Functions
PHP String Functions
HERE,
1
KAZI A S M-9765645688
The above example creates a simple string with the value of Alicia.
The variable name is then used in the string created using double quotes and its value is
interpolated at run time.
Output:
Alicia is friends with kalinda
In addition to variable interpolations, the double quote string can also escape more special
characters such as “\n for a linefeed, \$ dollar for the dollar sign” etc.
More examples Let’s suppose that we have the following code
<?php $pwd = "pas$word"; echo $pwd; ?>
Output:
NOTICE : Undefined variable
pas
executing the above codes issues a notice “Notice: Undefined variable”.
This is because $word is treated as a variable.
If we want the dollar sign to be treated as a literal value, we have to escape it.
<?php
$word="word";
$pwd = "pas\$word";
echo $pwd; ?>
Output:
pas$word
PHP Heredoc
This heredoc methodology is used to create fairly complex strings as compared to double quotes.
The heredoc supports all the features of double quotes and allows creating string values with
more than one line without php string concatenation.
Using double quotes to create strings that have multiple lines generates an error.
You can also use double quotes inside without escaping them.
The example below illustrates how the Heredoc method is used to create string values.
<?php
$baby_name = "Shalon";
echo <<<EOT
EOT;
?>
HERE,
<<<EOT is the string delimiter.
EOT is the acronym for end of text.
2
KAZI A S M-9765645688
It should be defined in its on line at the beginning of the string and at the end.
Note: you can use anything you like in place of EOT
Output:
When Shalon was a baby, She used to look like a "boy".
PHP Nowdoc
The Nowdoc string creation method is similar to the heredoc method but works like the way
single quotes work.
No parsing takes place inside the Nowdoc.
Nowdoc is ideal when working with raw data that do not need to be parsed.
The code below shows the Nowdoc implementation
<?php
$baby_name = "Shalon";
$my_variable = <<<'EOT'
EOT;
echo $my_variable;
?>
Output:
When $baby_name was a baby, She used to look like a "boy".
3
KAZI A S M-9765645688
4
KAZI A S M-9765645688