user1032531
user1032531

Reputation: 26331

PHP - Escape dollar sign

How can I modify a string to ensure that the dollar sign is preceded by an odd number of backslashes?

<?php
  $string = file_get_contents('somefile.txt');
  echo($string."\n");
  $string=str_replace ('$' , '\$' ,$string);
  echo($string."\n");
 ?>

somefile.txt

$first
\$second
\\$third
\\\$forth
\\\\$fifth

OUTPUT

    $first
\$second
\\$third
\\\$forth
\\\\$fifth
\$first
\\$second
\\\$third
\\\\$forth
\\\\\$fifth

Upvotes: 9

Views: 23302

Answers (2)

keyboardSmasher
keyboardSmasher

Reputation: 2811

This will do what you are asking.

$string = '$first \$second \\$third  \\\$forth \\\\$fifth';
echo $string."\n";
$string = str_replace(['\\','$'], ['', '\$'], $string);
echo $string."\n";

In a way, anyway. It removes all \ first and then it changes ALL $ to \$

BTW, echo isn't a function. :)

I'm not a regex wizard, so the following will add a backslash to all zero and even number \ preceding a $ (EXCEPT for the first one in the string):

$string = <<<'EOL'
$first $another \$second \\$third  \\\$forth \\\\$fifth
EOL;
var_dump($string);
$string = preg_replace('/([^\\\])(([\\\]{2})+)?\$/', '$1$2\\\$', $string);
var_dump($string);

Upvotes: 10

Evadecaptcha
Evadecaptcha

Reputation: 1451

You're in single quotes. In single quotes a dollar sign isn't parsed as anything. Nothing is auto parsed in single quotes in php. If you use double quotes they are automatically parsed:

echo "$var"; // this will print the value of $var;
echo '$var'; // this will print $var;
echo "\$var";// this escapes the dollar sign so it will print $var;

If the string was created in double quotes, you can't just escape the dollar sign afterwards, because it's already been parsed as a variable. Example:

$var = 'hello';
$str = "$var";

At this point you'd be trying to add an escape \$ when the value of $str is hello not $var.

Upvotes: 21

Related Questions