Obviously a job for preg_replace.
The regular expression to match would be something like this, but you'll have to sort out the values of $1, $2, etc and how to replace the matched strings, I don't have a test setup right now.
/((\W)(ab))|((ab)(/W))/