MANILA — Flanked by soldiers and officers, President Rodrigo Duterte of the Philippines on Tuesday declared the southern city of Marawi “liberated from terrorist influence,” five months after Islamic militants stormed the town, killing scores and sending thousands fleeing.

The president’s visit to Marawi came one day after the authorities declared government forces had killed the insurgency’s leaders in a gunfight. But gunfire could still be heard in pockets of the city, where about 30 militants, some of them foreigners, continued a last stand. At least 20 civilians remain hostages, the authorities said.

Those remaining fighters, officials said, were led by Mahmud bin Ahmad, a Malaysian terrorist who has helped fund the fighting in the Philippines’ restive south. Mr. Ahmad was a close associate of Isnilon Hapilon, an F.B.I.-wanted terrorist who was killed in Monday’s fighting. Mr. Hapilon was the leader of Abu Sayyaf, a terrorist group linked to the Islamic State.

The area still controlled by Mr. Mahmud and his fighters is “very much contained and controlled,” said Maj. Gen. Restituto Padilla, a military spokesman.