Use str_replace to replace key variable values

2

Good evening everyone! I'm trying to use the str_replace() method to replace a term within a variable, but it's not working.

foreach ($paginas as $pagina => $codigo) {

    if(!strcasecmp($atual, $pagina)) {

        str_replace("nav-link", "nav-link active", $codigo);

    }

    //Ao imprimir aqui, a substituição não surte efeito
    echo $codigo;

}

I thought it would be because the variable $codigo , which is the variable that foreach uses to assign the current value does not accept modifications, but maybe I'm wrong, so I came to ask them.

    
asked by anonymous 15.01.2018 / 02:02

1 answer

3

The correct would be this:

$codigo = str_replace('nav-link', 'nav-link active', $codigo);

The reason is that replace is not done in the original string . A new string is created with the changed value, which is returned by the function.

See a demo:

  

link

Unrelated to your specific case, but note that you can make multiple substitutions with a str_replace only, passing arrays instead of strings in the parameters.

In addition, if you prefer single quotes in strings in PHP, you will avoid unnecessary parse when searching for special characters and parameter interpolation.

See more details about str_replace in the manual:

  

link

    
15.01.2018 / 02:13