After South Africa set Sri Lanka a mammoth 507 to win, Philander took 2-34 and Rabada claimed 2-22 before Sri Lanka reached stumps on the third day on 130-4.
It took an unbroken partnership of 61 for the fifth wicket between captain Angelo Mathews and vice-captain Dinesh Chandimal to save Sri Lanka from an embarrassing three-day defeat, as they batted out the final hour of the day.
South Africa's dominance in the game was set up on day two when Quinton de Kock scored his third test century and Philander and Rabada shared eight wickets to bowl Sri Lanka out for 110.
The Sri Lankan paceman struck later in the same over to dismiss Hashim Amla for a duck, extending Amla's run without a half-century to 10 innings.
Elgar, whose 129 set up South Africa's first-innings total of 392, was next to go when he fell to Rangana Herath for 55, while JP Duminy (30) was trapped lbw by Lakmal on the stroke of lunch.
Du Plessis became Lakmal's fourth victim when he was caught behind by wicketkeeper Dinesh Chandimal, while De Kock fell in the same fashion to Lahiru Kumara.
Keshav Maharaj and Philander then put on an unbroken 32 for the eighth wicket to push the lead past 500, at which point Du Plessis declared with 47 overs remaining in the day, leaving Lakmal with figures of 4-69.
Philander made the initial inroads into the Sri Lankan line-up when he bowled Dimuth Karunaratne shortly before tea and then dismissed Kusal Mendis after the break.
Disclaimer: No Business Standard Journalist was involved in creation of this content
