Use a php variable within a function with str_replace

1

What I need is to replace what is in the variable ($ code) with (cars). For that I use a function with name (remove) using str_replace, the problem is that within the function remove does not recognize the variable ($ code) when I call the function . I hope you understand.

<?php
    $codigo = "autos";
    function quitar($mensaje){
        $mensaje = str_replace("$codigo","autitos",$mensaje);
        return $mensaje; 
    }

    // llamo a la funcion
    $nombre= quitar($nombre);
?>
    
asked by juan pablo 18.09.2018 в 17:06
source

2 answers

5

You have to pass the variable $codigo to the function to access its value from within and call this variable without quotes when doing str_replace .

The code works like this:

    $codigo = "autos"; 
        function quitar($mensaje,$codigo){ 
          $mensaje = str_replace($codigo,"autitos",$mensaje); 
           return $mensaje; 
        } 
        $nombre= quitar("Este es el día de autos",$codigo); 
        echo $nombre;

 //resultado Este es el día de autitos
    
answered by 18.09.2018 / 17:35
source
2

to use external variables in functions do the following

$codigo = "autos";
function quitar($mensaje) use ($codigo){
    $mensaje = str_replace("$codigo","autitos",$mensaje);
    return $mensaje; 
}
    
answered by 18.09.2018 в 17:16