How to escape special characters in sphinxQL fulltext search?

旧巷老猫 提交于 2019-12-07 12:00:30

There are corresponding functions EscapeString in each API ( php/python/java/ruby ) but to make escaping work with SphinxQL you have to write something similar in your application as SphinxQL hasn't such function.

The function itself is onliner

def EscapeString(self, string):
 return re.sub(r"([=\(\)|\-!@~\"&/\\\^\$\=])", r"\\\1", string)

you could easy translate it to code of your application.

The PHP version of the sphinxapi escape function did not work for me in tests. Also, it provides no protection against SQL-injection sorts of characters (e.g. single quote).

I needed this function:

function EscapeSphinxQL ( $string )
{
    $from = array ( '\\', '(',')','|','-','!','@','~','"','&', '/', '^', '$', '=', "'", "\x00", "\n", "\r", "\x1a" );
    $to   = array ( '\\\\', '\\\(','\\\)','\\\|','\\\-','\\\!','\\\@','\\\~','\\\"', '\\\&', '\\\/', '\\\^', '\\\$', '\\\=', "\\'", "\\x00", "\\n", "\\r", "\\x1a" );
    return str_replace ( $from, $to, $string );
}

Note the extra backslashes on the Sphinx-specific characters. I think what happens is that they put your whole query through an SQL parser, which removes escape backslashes 'extraneous' for SQL purposes (i.e. '\&' -> '&'). Then, it puts the MATCH clause through the fulltext parser, and suddenly '&' is a special character. So, you need the extra backslashes in the beginning.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!