Use str_replace to replace key variable values

Asked

Viewed 6,718 times

3

Good evening folks! I’m trying to use the method str_replace() to replace a term within a variable, but is having no effect.

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.

  • AH, correct. Now I went to read about the method on the PHP website and saw that the function returns a string or array with the values replaced. As I came from Java, I thought the method worked as replace(), with no return. Thanks for exclaiming.

  • It is a tip to always follow the PHP manual, because you are used to Java (which is a little more consistent in terms of nomenclature) will have many surprises, especially regarding the orders of the parameters (which vary greatly in PHP, often in the same function family).

  • 1

    It is. I had read about this method in the PHP manual, but had not put attention on the return part.

1 answer

4


That would be right:

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

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

See a demonstration:

http://ideone.com/m4jXYN

Not related to your specific case, but it is worth noting that you can make several replacements with one str_replace alone, passing arrays instead of strings in the parameters.

Additionally, if you prefer single quotes in strings in PHP, you will avoid a parse unnecessary in searching for special characters and interpolation parameters.

See more details about the str_replace in the manual:

https://secure.php.net/manual/en/function.str-replace.php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.