Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda