Sharapova was far from her best, hitting eight aces but as many double-faults.
Safaraova, the world number 25, was not overawed, and levelled the match with composure in the tie-break, but the top seed held her nerve, and after three hours and nine minutes finally set up a last-eight clash with Ana Ivanovic. The Serb was a straight-sets winner over eighth seed Nadia Petrova.
It was a similar grind for Petra Kvitova, who had to come back from losing the first set to beat Julia Goerges 2-6 7-6(4) 6-2.
Goerges had the support of her home fans, but could not finish the match off and tired as the Czech fifth seed ran away with the final set.
Third seed Angelique Kerber gave the locals something to cheer about though with a regulation 6-0 6-4 win over Anastasia Pavlyuchenkova of Russia.
Kerber now meets Yaroslava Shvedova after the Kazakh downed Spain's Carla Suarez Navarro 7-5 6-4 to book her place in the last eight of the claycourt tournament.
Second seed Li Na took just 74 minutes to seal her progression through to the quarter-finals with a 6-1 6-2 win over Mirjana Lucic-Baroni.
The Chinese star lost her serve twice against the Croatian qualifier, but was utterly dominant in capitalising on seven of 17 break points on her opponent’s serve.
It was a comprehensive victory for the 31-year-old and world number five, who already has a WTA singles title to her name this season and a 17-3 match record. Li now plays Petrova.
But there was disappointment for fourth seed Sara Errani, who was stunned 6-0 4-6 6-1 by American Bethanie Mattek-Sands in the late match.
Mattek-Sands will play Sabine Lisicki for a place in the semi-finals after the German saw off Jelena Jankovic of Serbia 7-6(3) 7-5.
Stuttgart Grand Prix results
Bethanie Mattek-Sands (U.S.) beat 4-Sara Errani (Italy) 6-0 4-6 6-1
Sabine Lisicki (Germany) beat Jelena Jankovic (Serbia) 7-6(3) 7-5
1-Maria Sharapova (Russia) beat Lucie Safarova (Czech Republic) 6-4 6-7(3) 6-3
5-Petra Kvitova (Czech Republic) beat Julia Goerges (Germany) 2-6 7-6(4) 6-2
Ana Ivanovic (Serbia) beat 8-Nadia Petrova (Russia) 6-4 6-3
Yaroslava Shvedova (Kazakhstan) beat Carla Suarez Navarro (Spain) 7-5 6-4
3-Angelique Kerber (Germany) beat Anastasia Pavlyuchenkova (Russia) 6-0 6-4
2-Li Na (China) beat Mirjana Lucic-Baroni (Croatia) 6-1 6-2
Marrakech Grand Prix Results
6-Francesca Schiavone (Italy) beat Simona Halep (Romania) 6-3 6-2
5-Kiki Bertens (Netherlands) beat Flavia Pennetta (Italy) 7-6(0) 4-6 6-4
7-Kristina Mladenovic (France) beat Yulia Putintseva (Kazakhstan) 6-3 6-3
Silvia Soler Espinosa (Spain) beat Olga Puchkova (Russia) 6-0 6-3
Lourdes Dominguez Lino (Spain) beat 9-Tsvetana Pironkova (Bulgaria) 1-6 6-4 6-3
Mandy Minella (Luxembourg) beat 4-Kaia Kanepi (Estonia) 3-6 6-4 6-3