Problem with str_replace php

9

str_replace does not compare the entire string, it only compares half the string.

I have an associative array:

$arrayFrutas = [
    "banana" => f.banana,
    "bananaGrande" => f.banana_grande
];

So I have a String:

$stringParameters = "bananaGrande = 1";

I want to replace the bananaGrande from $stringParameters with f.banana_grande from $arrayFrutas .

For this I take the $arrayFrutas key and look for its occurrence within $stringParameters , so I created a method that is just below:

public function pegarCampoCorretoAliasFilter($string, $classPerm)
{
    foreach($classPerm as $key => $value) {
        $string = str_replace($key, $classPerm[$key], $string);
    }
    return $string;
}

Where in my pegarCampoCorretoAliasFilter($string, $classPerm){} method:   $ string = $ stringParameters and $ classPerm = $ arrayFrutas .

Here's the problem that is happening instead of just changing the bananaGrande for the f.banana_grande he makes an ante exchange because he finds the word banana in the string that I pass there and the final result is as follows:

  

f.f.banan_grande

In other words, I do not want it to compare (banana = bananaGrande) because besides being not true there is not even a space in the string, I want it to compare the string and change it if the whole string is up to your space is equal to the key I am passing, producing this output:

  

f.banana_grande

How could I solve this?

    
asked by anonymous 02.10.2017 / 13:01

2 answers

7

You can use regular expression. The \ b forces the search for the whole word.

$text = preg_replace('/\bbananaGrande\b/', 'NEW', $text);

If the text contains UTF-8 you will have to do so:

$text = preg_replace('/\bbananaGrande\b/u', 'NEW', $text);

Getting something close to this:

$text = "bananaGrande = 1"; $text2 = preg_replace('/\bbanana\b/', 'NEW', $text);

$text = preg_replace('/\bbananaGrande\b/', 'NEW', $text);


echo($text2 . '<br />'); echo($text);

As you can see, he replaces when he found the complete word:

    
02.10.2017 / 13:27
4

No, you do not need REGEX, you can use strtr , it has behavior other than str_replace :

$arrayFrutas = [
    "banana" => 'f.banana',
    "bananaGrande" => 'f.banana_grande'
];


$string = 'bananaGrande = 1';

echo strtr($string, $arrayFrutas);

Result:

f.banana_grande = 1

You can give this (SOen) explanation about difference between str_replace and strtr .

    
02.10.2017 / 13:49