Escaping special characters in SphinxSE

给你一囗甜甜゛ 提交于 2019-12-05 13:26:14

Character escaping in Sphinxql is a tricky subject... I'm not sure if it is fully officially resolved. mysql_real_escape_string won't handle the special Sphinx query characters.

They do provide an escape function in sphinxapi.php:

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

Note that this won't specifically handle the SQL escape characters (for example, no single quote replacement). Actually, I tested it, and it doesn't even work just for Sphinx characters.

You need 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.

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