たぶんこれでOK

http://ideone.com/NM6es6