php+mysql fuzzy query function

The general fuzzy query statement is as follows: 

SELECT Field FROM Table WHERE A Field Like Condition

Among them, SQL provides four matching modes for conditions :

1, %: Indicates any 0 or more characters. It can match characters of any type and length. In some cases, if it is Chinese, please use two percent signs (%%).
For example, SELECT * FROM [user] WHERE u_name LIKE '%three%'
will find all records with "three" in u_name as "Zhang San", "Zhang Maosan", "Three-legged Cat", " Tang Sanzang ", etc. come out.
In addition, if you need to find out the records with both "three" and "cat" in u_name, please use and condition
SELECT * FROM [user] WHERE u_name LIKE '%three%' AND u_name LIKE '%cat%'
If using SELECT * FROM [user] WHERE u_name LIKE '%san%cat%'
can search for "three-legged cat", but cannot search for the qualified "Zhang Maosan".

2, _: Indicates any single character. Match a single arbitrary character, it is often used to limit the character length of the expression statement:

such as SELECT * FROM [user] WHERE u_name LIKE '_三_'
only finds " Tang Sanzang " such that u_name is three words and the middle word is " Three";

another example is SELECT * FROM [user] WHERE u_name LIKE 'three__';
Only find "three-legged cat" such that the name is three words and the first word is "three";

3, [ ]: Indicates one of the characters listed in brackets (similar to regular expressions). Specify a character, string, or range to match against any of them.

For example, SELECT * FROM [user] WHERE u_name LIKE '[Zhang Li Wang] San'
will find "Zhang San", "Li San", "Wang San" (instead of "Zhang Li Wang San");

such as [ ] A series of characters (01234, abcde, etc.) can be abbreviated as "0-4", "ae"
SELECT * FROM [user] WHERE u_name LIKE 'old [1-9]'
will find "old 1", "Old 2", ..., "Old 9";

4, [^ ]: Indicates a single character not listed in parentheses. Its value is the same as [], but it requires the matched object to be any character other than the specified character.

For example, SELECT * FROM [user] WHERE u_name LIKE '[^Zhang Liwang]San'
will find "Zhao San", "Sun San", etc. who are not surnamed "Zhang", "Li" and "Wang";

SELECT * FROM [user] WHERE u_name LIKE 'Old [^1-4]';
will exclude "Old 1" to "Old 4", look for "Old 5", "Old 6", ...

5, when the query content contains wildcards,

due to wildcards Because of this, the query for special characters "%", "_", and "[" cannot be implemented normally, but it can be queried normally by enclosing the special characters with "[ ]". From this we write the following function:

function sqlencode(str)
str=replace(str,"[","[[]") '此句一定要在最前
str=replace(str,"_","[_]")
str=replace(str,"%","[%]")
sqlencode=str
end function

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325315085&siteId=291194637