There are four ways of specifying a string in php:
- Using a single quote$str = 'Hello World. This might be a php $variable';echo $str; // Outputs: Hello World. This might be a php $variable
Since the string was wrapped in single quote, php engine will not try to interpret $variable as actual variable and the contents of what you see in the quotes will be echoed.
- Using double quote$variable = 'random text'; $str = "Hello World. This will be interpreted as $variable";echo $str; // Outputs: Hello World. This will be interpreted as random text
In this example, php will try to find a variable named $variable and use its contents in the string.
- Heredoc syntax
Heredoc is useful for things such as what you wanted to do - you have a mix of variables, single quotes, double quotes and escaping all that can be a mess. Hence, good php people implemented the following syntax for us:
$str = <<<EOF
<img src="$directory/images/some_image.gif" alt='this is alt text' /> <p>Hello!</p>
EOF;
What will happen is that PHP engine will try to interpret variables (and functions, but I won't post examples on how to do that since it's available at php.net), however you wrapped the string with <<
- Nowdoc syntax$str = <<<'EOF'Hello! This wants to be a $variable but it won't be interpreted as one!EOF;
It's the same as using a single-quoted string - no variable replacements occur, and to specify something as nowdoc - simply wrap the delimiter with single quote characters as shown in the example.
If you are able to understand these four principles, problems with quotes in your string should go away :)
0 comments:
Post a Comment