Look at preg_replace(). The expression might be a bit tricky, so you'll probably have to attack it bit by bit. I suggest starting small, just try to solve mini problems. For example, just write an expression that matches the first line and extracts the parts you want. Then do the same for the second line. Then figure out how to combine your patterns into a single pattern, or keep them separated and assemble your final string using the matches arrays of your individual preg_match() calls.