Given answers don't answer the question.
Although there is no way for the general purpose "string sanitization", one may notice that the given string is a very special one.
And the only way to sanitize it is whitelisting.
A best way to sanitize this string would be to have both parts separated and then both checked against whitelist.
So, instead of having this string whole, I'd have it in 2 variables, $_GET['orderby']
and $_GET['dir']
.
And so the code would be
$allowed = array("dest","foo","whatever");
$key = array_search($_GET['orderby'], $allowed));
$orderby = $allowed[$key];
$dir = $_GET['dir'] == 'DESC' ? 'DESC' : 'ASC';
$query = "SELECT * FROM t ORDER BY $orderby $dir";