Wilfried Bony missed from the spot as Algeria edged past the Ivory Coast in a dramatic penalty shoot-out to reach the Africa Cup of Nations semi-finals.
Sofiane Feghouli had fired Les Fennecs into a 20th-minute lead and then saw teammate Baghdad Bounedjah squander a second-half penalty before Jonathan Kodjia levelled in a tight encounter in Suez.
But substitute Bony and skipper Serey Die both failed from the spot to send Algeria through 4-3 on penalties to set up a last-four clash with Nigeria in Cairo on Sunday.
Kodjia failed to make the most of two early chances and Algeria took full advantage when Amir Bensebaini found space on the left with 20 minutes gone and crossed for Feghouli to sweep a shot past keeper Sylvain Gbohouo.
They should have increased their lead after Bounedjah had been felled by Gbohouo just 23 seconds after the restart, but the striker crashed the spot-kick against the crossbar, and his side was made to pay with 62 minutes gone when Kodjia fired low past Rais Mbohli to level.
Mamadou Bagayoko cleared a Mahrez shot off the line as Algeria responded, but the sides could not be separated in the 90 minutes and after Gbohouo had beaten away substitute Islam Slimani's extra-time header, penalties were required.
Tunisia later ended Madagascar's remarkable run at the tournament when they beat the rank outsiders 3-0 in their quarter-final, notching their first win of the tournament in the process.
Madagascar, a country with little football tradition and who had not been expected to progress beyond the group stage on their first appearance at the finals, held out until the second half when they were undone by Ferjani Sassi's deflected shot.
Youssef Msakni added a second on the hour for the Carthage Eagles, ranked 25th in the world against Madagascar's 107th, and substitute Naim Sliti finished it off on the break in stoppage time to earn them a semi-final against Senegal on Sunday.
"Today, the bar was too high, Tunisia were too strong for us, they were a very well-organised team. The result was logical," said Madagascar coach Nicolas Dupuis, who also coaches French fourth-tier side Fleury.
"I am very proud of the players and what they have done at this tournament, it's exceptional. I take off my hat to them."
Tunisia had drawn their previous four matches at the tournament, beating Ghana on penalties in the last 16.