Can I go outside the airport for few hours and come back before my
flight?
Yes as a South African citizen, you can get an Evisa for tourist visits of up to 180 days starting from the first entry date, valid for touristic purposes not exceeding 30 days per entry. Also you do not need to pay for your visa fee and it will be a multiple entry Evisa.
Source: Evisa
As you are traveling on Turkish Airlines, you are also entitled to a complimentary hotel stay from Turkish Airlines. A complimentary hotel accommodation (maximum 2 nights) will be provided to passengers when there are more than 10 hours (for economy cabin passengers) and 7 or more hours (for business cabin passengers) if they are traveling on Turkish Airlines.
Source: Turkish Airlines
So basically an 18 hour layover is a very long transit at Attaturk airport. Not only could you visit Istanbul for sightseeing, you could also take a complimentary hotel stay provided by Turkish airlines as well.
Credit:stackoverflow.com‘