1

I want to delete any dollar sign($) from a PHP variable only if it surrounds a word.

I know how to replace every $ with empty space to look like is deleted, for example:

  <?php 

      $string = 'Hello $George$';
      $string = str_replace('$', '', $string);
      echo $string; // Prints: Hello George


   ?>

But the code above is also removing $ that are not surrounding a word, for example:

<?php 

      $string = 'Hello $George$, are you $ok?';
      $string = str_replace('$', '', $string);
      echo $string; // Prints Hello George, are you ok?

   ?>

I've been trying for many hours to solve this problem but didn't manage to puzzle it out, any help is appreciated.

Mr George
  • 39
  • 7
  • 1
    I'm not sure how it would replace the $ from $ok in `$string = "Hello $George$, are you $ok?";` ... because it would actually already have replaced $ok with the value of that variable while it was assigning it to $string. – IncredibleHat Jan 19 '18 at 20:39
  • Simple comment answer will probably follow by someone else but simple. Use Regular Expressions to "match" the beginning and ending "$" symbols. – Musk Jan 19 '18 at 20:40
  • 2
    as another recommendation when setting your strings use SINGLE QUOTE ' to prevent php from attmepting to parse the $string as a variable – happymacarts Jan 19 '18 at 20:41
  • Unless you meant to write: `$string = 'Hello $George$, are you $ok?';` (note the single quotes)... but then you'd end up having to `eval()` that string to get $ok to replace. – IncredibleHat Jan 19 '18 at 20:41

1 Answers1

10

First of all, i will answer your question

Use preg_replace instead, that is uses with a pattern that detects only those dollar signs, that are surrounding a word.

$string = preg_replace('/\$(\w+)\$/', '$1', $string);

Now an improvement for your code

As mentioned in the comments of your question, you would need to surround your string with single quotes (') to prevent PHP from replacing your words, that are prefixed by a dollar sign, with their corresponding variables.

A good source to understand the differences between double- and single-enquoted strings can be found from this question.

Philipp Maurer
  • 2,480
  • 6
  • 18
  • 25