文本替换中的问题

I am trying to make a text replacer but since there are letters repeated i keep getting things i dont want. Does anyone know how i can do this?

Input

function image($img) { 
      $img = ereg_replace("a","<img src=r/a.png>", $img); 
      $img = ereg_replace("b","<img src=r/b.png>", $img); 
      $img = ereg_replace("c","<img src=r/c.png>", $img); 
      return $img; 
} 

 $img = "abc"; 
 echo image($img); 

Output

<img sr<img src=r/c.png>=r/a.png><img sr<img src=r/c.png>=r/b.png><img src=r/c.png> 

Output I Want

<img src=r/a.png><img src=r/b.png><img src=r/c.png> 

Try this, may be insufficient but it will satisfy your requirement:

function image($img) {
      $data=""; 

      for( $i = 0; $i <= strlen($img); $i++ ) {
        $char =substr( $img, $i, 1 );
        switch($char)
        {
            case 'a':
                 $data .="<img src=r/a.png>";
                 break;
            case 'b':
                 $data .="<img src=r/b.png>";
                 break;
            case 'c':
                 $data .="<img src=r/c.png>";
                 break;
            default:
            break;
        }
      }
      return $data; 
} 

 $img = "abc"; 
 echo image($img);

Problem with "c" your "a" and "b" replacing correctly but when it reach "c" there are many "c" cause "src" also added so it replaces all "c"

try with single statement

function image($img) { 
      $img = ereg_replace("abc","<img src=r/a.png><img src=r/b.png><img src=r/c.png>", $img); 
      return $img; 
} 

 $img = "abc"; 
 echo image($img); 

Also ereg_replace() has been deprecated

Here is what I tried:-

function image($img) { 
        for($i=0;$i < strlen($img);$i++){
            $letterarray[]=$img[$i];
        } 
        $a=0;
        foreach ( $letterarray as &$value) { // reference
           $value= str_replace($value, "<img src=r/$value.png>", $value);
            $a++;
            $ab[] = $value;
        }
      return implode("",$ab);
} 

 $img = "abc"; 
 echo image($img); 

Here in the function image(), you don't need to specify the alphabets contained in $img