0

Forgive me for my wording of the question. It could be that str_replace is replacing these characters as it is supposed to and that I don't properly understand the fundamentals of what going on. However here is my question.

I'm trying to use str_replace to create a function in PHP that replaces abbreviated names with full version of the names. The problem is that in some cases the abbreviations are single letter abbreviations and this causes problems. For example:

<?php
//Abreviated Set Names
function changer($string_to_replace){
    $ab_name   = array('A','APP','ANG',);
    $full_name = array('Alley Cat', 'Apples', 'Angela');
    return str_replace($ab_name, $full_name, $string_to_replace);
}

echo changer('APP');
?>

When I call this function and pass it A i will return "Alley Cat" which is what I want it to do. However, if I pass it "APP" instead of returning "Apples" it returns "Alley CatPP". Obviously not what I want it to do. I've searched around quite a bit and have not been able to find a solution for this. Any help would be much appreciated.

Kind Regards Sour Jack

ptCoder
  • 2,229
  • 3
  • 24
  • 38
Sour Jack
  • 71
  • 8

1 Answers1

0

Benoit (and everyone else).

Thank you for your answers. I also found this code which after testing works very well.

<?php
$state = 'AVR';
echo convert_state($state);

function convert_state($key) {
    $a2s = array( 
        'A'=>'Apples',
        'AVR'=>'Abby Road'
    );
    $array = (strlen($key) <=3 ? $a2s : array_flip($a2s));
    return $array[$key];
}
?>
Sour Jack
  • 71
  • 8
  • Also note, the $array variable can be modified to accomodate different string lengths by changing the value following the <= – Sour Jack May 15 '15 at 16:45