An attack on a university in Pakistan which left at least 20 people dead has been ended by security forces.

The attackers triggered a heavy gun battle with police and army troops in a town near Peshawar, but officials said the operation to clear the site had now finished, and that four gunmen were killed.

The attack stirred grim memories of the Peshawar school attack in 2014 that killed more than 150 people, mostly children, and shocked the nation. It also prompted the Pakistani prime minister to pledge the country will wipe out the "menace of terrorism".

The attack began shortly after the Bacha Khan University opened for classes in the town of Charsadda, some 21 miles outside Peshawar, said deputy commissioner Tahir Zafar.

As police and soldiers rushed to the campus, the attackers traded gunfire with the troops and several explosions were heard from the area of the university. The attackers were later contained inside two university blocks where the troops killed them, the army said.

A chemistry professor and a student were among those killed, said Mr Zafar, adding that it was not initially clear how many attackers managed to penetrate the campus. Television footage showed heavy military presence at the university, troops rushing in and people fleeing. Ambulances were at the scene and the wounded were taken to hospital.

Pakistani prime minister Nawaz Sharif vowed to fight to the end and destroy the Taliban and other militants.

"We are determined and resolved in our commitment to wipe out the menace of terrorism from our homeland," Mr Sharif said.

A Taliban leader, Khalifa Umar Mansoor, claimed responsibility for the attack. Mansoor, who was the mastermind behind the Peshawar school attack, said a four-man Taliban team carried out the assault. He said it was in revenge for the scores of militants the Pakistani security forces have killed in recent months.

However, a spokesman for the main Taliban faction in Pakistan later disowned the group behind the attack, describing the assault as "un-Islamic."

Mohammad Khurasani also denied earlier reports that he had endorsed Mansoor's claim and said that those who carried out such attacks would be tried before an Islamic, or Sharia court.

Such statements from among the Taliban are not uncommon since the group has many loosely linked factions and is indicative of the deep divisions and splits among the insurgents.

The Bacha Khan University is named after the founder of a liberal, anti-Taliban political party. The Pakistani Taliban have in the past targeted the party for its anti-militant policies.