Find words starting and ending with dollar sign $ in PHP

I am looking to find and replace words in a long string. I want to find words that start like this: $ test $ and replace nothing.

I've tried a lot of things and can't figure out the regex. This is the last thing I tried:

preg_replace("/\b\\$(.*)\\$\b/im", '', $text);

      

No matter what I do, I cannot get it to replace words that start and end with a dollar sign.

+3


source to share


3 answers


Use single quotes instead of double quotes and remove double escape.

$text = preg_replace('/\$(.*?)\$/', '', $text);

      

Also the word boundary \b

does not consume any characters, it states that there is a word character on one side and not on the other. You need to remove the word border for this to work and you don't have anything containing words in your regex, so the modifier i

is useless here and you don't have anchors, so remove the m

(multiline).

Also *

a greedy operator. This way .*

will match as much as it can and allow the remainder of the regex to match. To be clear, it will replace the entire line:

$text = '$fooo$ bar $baz$ quz $foobar$';
var_dump(preg_replace('/\$(.*)\$/', '', $text));
# => string(0) ""

      



I recommend using the unwanted operator *?

here. Once you point the question mark, you point out ( not greedy ), once you find the ending $

... stop, you're done.)

$text = '$fooo$ bar $baz$ quz $foobar$';
var_dump(preg_replace('/\$(.*?)\$/', '', $text));
# => string(10) " bar  quz "

      

Edit

To fix your problem, you can use \S

that matches any non-whitespace.

$text = '$20.00 is the $total$';
var_dump(preg_replace('/\$\S+\$/', '', $text));
# string(14) "$20.00 is the "

      

+4


source


There \b

are three different positions as word boundaries :

  • Before the first character in the string if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in a string, where one is a word character and the other is not a word character.

$

is not a word symbol, so don't use \b

or it won't work. Also, there is no need for double escaping and no need for modifiers im

:



preg_replace('/\$(.*)\$/', '', $text);

      

I would use:

preg_replace('/\$[^$]+\$/', '', $text);

      

+3


source


You can use preg_quote

to help you "quote":

$t = preg_replace('/' . preg_quote('$', '/') . '.*?' . preg_quote('$', '/') . '/', '', $text);

echo $t;

      

From the docs:

This is useful if you have a runtime string that needs to be matched in some text, and the string might contain special regular expressions.

Regular expression special characters:. \ + *? [^] $ () {} =! <> |: -

+1


source







All Articles