Pakistan kept their nerve to avoid a huge shock on Saturday, beating a spirited Afghan side by three wickets with just two balls to spare to keep their World Cup semi-final hopes alive.

All-rounder Imad Wasim hit Afghanistan skipper Gulbadin Naib for a boundary through the covers to seal the win off the fourth ball of the last over, prompting chaotic scenes as fans poured onto the Headingley pitch.

Pakistan, chasing a modest 228-run target, were in grave danger at 156 for six in the 39th over. But man-of-the-match Imad (49 not out) and Shadab Khan (11) put on 50 for the seventh wicket to revive their hopes.

The third consecutive victory lifts Pakistan into fourth place in the 10-team table, above hosts England, with the top four qualifying for the semi-finals. If they win their final game against Bangladesh and England fail to win both of their last two matches, against India and New Zealand, Pakistan are almost certain to progress.

“Thank you all the fans, they cheered every ball. It is a great win for us on not an easy pitch,” said Pakistan captain Sarfaraz Ahmed.

“We all know that it is not easy to win our last four games,” he said.

“We go match by match. We will all be watching India v England tomorrow (Sunday).”

Pakistan Prime Minister Imran Khan, a World Cup-winning captain in his cricket days, tweeted his congratulations to the team for “keeping their nerve under pressure”.