A way of doing that with a regular expression:
<?php
// Lucene characters that need escaping with \ are + - && || ! ( ) { } [ ] ^ " ~ * ? : \
$luceneReservedCharacters = preg_quote('+-&|!(){}[]^"~*?:\\');
$query = preg_replace_callback(
    '/([' . $luceneReservedCharacters . '])/',
    function($matches) {
        return '\\' . $matches[0];
    },
    $query);
?>