Leo Galleguillos
Leo Galleguillos

Reputation: 2730

regular expression - dollar signs within border characters

In php, I am trying to match two consecutive dollar signs surrounded by border characters, but I can't seem to figure out the pattern. Here are example strings I want to match:

$string = '$$';
$string = ' $$ ';
$string = "\n$$\n";

Here are the patterns I have tried:

$pattern = '/\b\$\$\b/';     // First attempt at escaping dollar signs
$pattern = '/\b\\\$\\\$\b/'; // Maybe backslashes need to be escaped
$pattern = '/\b$$\b/';       // Maybe dollar signs shouldn't be escaped
$pattern = "/\b\$\$\b/";     // Maybe we need double quotes for special characters
$pattern = "/\b\\\$\\\$\b/"; // Double quotes and double-escaping

None of the above patterns return any matches when running:

preg_match($pattern, $string);

Any ideas? Thank you.

Upvotes: 1

Views: 208

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521639

Both the OP and @JonStirling basically cracked this problem before I posted this answer. Your very first pattern \b\$\$\b is correct, at least from the point of view of properly escaping dollar sign. The issue is that word boundaries mainly deal with boundaries between words and non words. Since dollar sign is not a word character, \b is not behaving as you want.

Here is an alternative which uses lookarounds as a proxy for word boundaries:

$string = ' $$';
$pattern = '/(?<=\s|^)\$\$(?=\s|$)/';
echo preg_match($pattern, $string, $match);

The logic here is that we check for either whitespace or the start/end of the string, on both sides of the dollar signs.

Upvotes: 2

Related Questions