[eluser]sophistry[/eluser]
yes, tags with spaces makes it a lot more complicated! ;-)
basically, it will be easier for you if you approach it in a multi-step way rather than trying to stuff everything into a giant regex.
another approach is to strip out the "a" and "img" tags, do the replacement and stuff the a and img tags back in where they were removed. this could get pretty devilish too.
experiment and post your code and results.