Home
Web design
Software
Articles
Site Map

> Articles > PHP articles > Avoiding prefixing $, \, ", ' symbols with slashes

Avoiding prefixing $, \, ", ' symbols with slashes

  • 1. Some PHP semantics.

In PHP a string literal can be specified in several ways.
  1. Single quoted:
        $str 'some text, single \'quote, $dollar sign , "double quotes"';
    only single quoted have to be prefixed by slashes inside that string.

  2. Double quoted:
        $str "text, double quote\", \$dollar sign, 'single quotes'";
    dollar sign, double quotes and slash should be prefixed by slashes here.

  3. Heredoc syntax:
        $str = <<<EOD
        some text here
        "quotes', 
    \$ dollar sign
        EOD;
    only dollar sign has to be prefixed by slash, also \r is not allowed inside.

  • 2. Alternative solution.

Starting from PHP 4 we can control the way PHP buffers the output.
We can stop immediate output at any moment, and redirecting all the output to internal PHP buffer, later we can read from that buffer.

That allows us to specify a string literal not prefixing any symbols with slashes, but that way we can not use <? and ?> inside the text block.

    <? ob_start(); ?>

Anything here, $dollar sign, "any quotes', slashes \ /, ...

    <? $str ob_get_contents(); ob_end_clean(); ?>

This is an example of using PHP buffering to avoid extra slashes, saving text in the variable $str.
The only disadvantage is that it's impossible to use PHP tags in a straight way inside that text block.
There is a workaround for that, replacing
<? and ?>
with
<?='<?';?> and <?='?>';?>


Copyright © Val Samko, DigiWays. Written by Valentin Samko mailto:val@digiways.com