I'm pulling a 5x5 array from a larger array. The small sub-array (call it S) can contain any combination of the symbols A, B or 0. What I'd like to do is: if the array contains any matching pairs between the center cell and a border cell with a 0 between them, we change the zero to match.

To enumerate (and make perfectly clear what I'm talking about) here are all the possible cases (using ? as a wildcard):

 ? ? A ? ? ? ? A ? ? 
 ? ? 0 ? ? ? ? A ? ?
 ? ? A ? ? ----> ? ? A ? ?
 ? ? ? ? ? ? ? ? ? ? 
 ? ? ? ? ? ? ? ? ? ?

 ? ? ? ? A ? ? ? ? A 
 ? ? ? 0 ? ? ? ? A ?
 ? ? A ? ? ----> ? ? A ? ?
 ? ? ? ? ? ? ? ? ? ? 
 ? ? ? ? ? ? ? ? ? ?

 ? ? ? ? ? ? ? ? ? ? 
 ? ? ? ? ? ? ? ? ? ?
 ? ? A 0 A ----> ? ? A A A
 ? ? ? ? ? ? ? ? ? ? 
 ? ? ? ? ? ? ? ? ? ?

 ? ? ? ? ? ? ? ? ? ? 
 ? ? ? ? ? ? ? ? ? ?
 ? ? A ? ? ----> ? ? A ? ?
 ? ? ? 0 ? ? ? ? A ? 
 ? ? ? ? A ? ? ? ? A

 ? ? ? ? ? ? ? ? ? ? 
 ? ? ? ? ? ? ? ? ? ?
 ? ? A ? ? ----> ? ? A ? ?
 ? ? 0 ? ? ? ? A ? ? 
 ? ? A ? ? ? ? A ? ?


 ? ? ? ? ? ? ? ? ? ? 
 ? ? ? ? ? ? ? ? ? ?
 ? ? A ? ? ----> ? ? A ? ?
 ? 0 ? ? ? ? A ? ? ? 
 A ? ? ? ? A ? ? ? ?


 ? ? ? ? ? ? ? ? ? ? 
 ? ? ? ? ? ? ? ? ? ?
 A 0 A ? ? ----> A A A ? ?
 ? ? ? ? ? ? ? ? ? ? 
 ? ? ? ? ? ? ? ? ? ?


 A ? ? ? ? A ? ? ? ? 
 ? 0 ? ? ? ? A ? ? ?
 ? ? A ? ? ----> ? ? A ? ?
 ? ? ? ? ? ? ? ? ? ? 
 ? ? ? ? ? ? ? ? ? ?

Also these rule(s) stack so you can have something like this:

 A ? ? ? ? A ? ? ? ? 
 ? 0 ? ? ? ? A ? ? ?
 ? ? A 0 A ----> ? ? A A A
 ? ? ? ? ? ? ? ? ? ? 
 ? ? ? ? ? ? ? ? ? ?


And likewise for B. There's obviously a huge amount of symmetry in this situation, but I have no idea how to exploit it to avoid writing out 8 separate replacement rules. Seems like there should be clever way to just write one replacement rule that does the job. I'm stumped on that though :) 

Edit: I'm using Mathematica 10