How to implement the wildcard * matching function in MYSQL Query and bitsCN.com
When sending a short message on the site today, you may encounter a function that is to perform a wildcard search for an account.
The following situations may be used for search:
Sunzhongshan string searches without wildcards
Sun * starts with sun
* Shan ends with shan.
Sun * shan starts with sun and ends with shan
* Zhong * contains zhong
Sun * ong * starts with sun and contains ong
The first thought is to make a judgment. if it starts with "*", how should it be handled. Then process the strings one by one using the * array separator.
In this case, a large number of functions are used for judgment, which is a waste of resources. So I decided to rethink my ideas .....
.......................
The last code written by sun * is usename LIKE 'Sun %'
* Zhong * The last written code is usename LIKE '% zhong %'
......................................
In this way, I want to replace * with % before processing.
Taking sun * zhong * as an example, you can replace it with sun % zhong %, which seems to be implemented, but it is difficult to separate and convert
Finally, we can use %, % to replace it. after replacement, sun %, % zhong %, %
Then, the trim () function is used to process the preceding and following % symbols.
Then it is split into arrays by explode (). The preceding string is split into arrays (0 => sun %, 1 => % zhong %, 2 =>)
If there are spaces, you can skip the loop.
Example code completed:
$ SQL = "SELECT autoid FROM users WHERE 1 = 1 ";
$ Str1 = 'Sun * zhong *';
$ Str11 = str_replace ('*', '%, %', $ str1 );
$ Str12 = trim ($ str11, '% ');
$ Str13 = explode (",", $ str12 );
Foreach ($ str13 as $ strStr ){
If (emptyempty ($ strStr )){
Continue;
}
$ SQL. = "AND username LIKE '". $ strStr ."'";
}
Echo $ SQL;
// Execution result:
// SELECT autoid FROM users WHERE 1 = 1 AND username LIKE 'Sun % 'AND username LIKE' % zhong %'
?>
From: the growth path of golden pig's PHP
BitsCN.com