Escape string for use in MySQL fulltext search

后端 未结 1 1239
悲&欢浪女
悲&欢浪女 2021-02-02 13:36

I am using Laravel 4 and have set up the following query:

if(Input::get(\'keyword\')) {
    $keyword = Input::get(\'keyword\');
    $search = DB::connection()-&g         


        
1条回答
  •  梦毁少年i
    2021-02-02 14:32

    Only the words and operators have meaning in Boolean search mode. Operators are: +, -, > <, ( ), ~, *, ", @distance. After some research I found what word characters are: Upper case, Lower case letters, Numeral (digit) and _. I think you can use one of two approaches:

    1. Replace all non word characters with spaces (I prefer this approach). This can be accomplished with regex:

      $search = preg_replace('/[^\p{L}\p{N}_]+/u', ' ', $keyword);
      
    2. Replace characters-operators with spaces:

      $search = preg_replace('/[+\-><\(\)~*\"@]+/', ' ', $keyword);
      

    Only words are indexed by full text search engine and can be searched. Non word characters isn't indexed, so it does not make sense to leave them in the search string.

    References:

    • Boolean Full-Text Searches
    • Fine-Tuning MySQL Full-Text Search (see: "Character Set Modifications")
    • PHP: preg_replace
    • PHP: Unicode character properties
    • PHP: Possible modifiers in regex patterns

    0 讨论(0)
提交回复
热议问题