Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
Unable to replace `$_` by something else in preg_replace()

I am investigating, but I am not able to find the solution to this.

The idea is to replace the characters $_ from a string with something else. If you remove the dollar sign from the $search variable, it kind of works (but not in a desirable way).

It is not working because the dollar sign is a special character, but I cannot find how to scape it.

This is what I have:

$search = '$_'; // replace to '_' OR '[$_]' it returs "$1" instead of "1"
$replace = 1;
$regex = '#".*?"(*SKIP)(*FAIL)|\b' . $search . '\b#s';

$fullInput = '"$_" $_';

$r = preg_replace([$regex], $replace, $fullInput);

echo $r . PHP_EOL;

// Output with current code : "$_" $_
// Output with '_' or '[$_]': "$_" $1
//
// Expected result: "$_" 1 

To have into account, if the text is between quotes, it should not be replaced.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You may use this regex for search:

"[^\\"]*(?:\\.|[^\\"]*)*"(*SKIP)(*F)|\$_

and replace it with [$0]

Pattern before | matches a double quoted string allowing an escaped quote in between. Pattern after | matches $_.

RegEx Demo

RegEx Details:

  • "[^\\"]*(?:\\.|[^\\"]*)*": Match a double quoted string. We allow escaped characters in this match.
  • (*SKIP)(*F): Skip and fail this match
  • |: OR
  • \$_: Match literal text $_

Code:

$search = '$_';
$replace = '[$0]';
$regex = '/"[^\\"]*(?:\\.|[^\\"]*)*"(*SKIP)(*F)|' . preg_quote($search, '/') . '/';
$fullInput = '"$_" $_';
$r = preg_replace($regex, $replace, $fullInput);
echo $r . PHP_EOL;

Output:

"$_" [$_]
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!