1

I'm not too sure how to correctly explain this, but I'll try my best. I am using ajax to filter through certain posts based on a text input field. This then lists all posts including the letters and numbers a user input. Pretty basic stuff.

Now, my client wants to add a "Smart Search" feature. Basically, if a user enters "0123" they want it to list all posts with titles that include "0123" as well as "o123". The same thing needs to happen with "s" and "5". So if a user types "1234s" it will list all posts that include "1234s" and "12345". Is there anyway to do this?

Here is what I have so far, numberchar is the name of the text input

$categoryparentfilter = "SELECT ID FROM `wp_posts` WHERE `post_title` LIKE '".trim($_POST['numberchar'])."%' order by ID desc";
Astrokotch
  • 35
  • 2
  • this could get quite hairy, with the number of possibilities. Are you also going to account for 1 looking like "I" or a lower case "L", 8 looking like "B", 6 looking like "G", 2 looking like "Z"? If so, "0123" could be "o123", or "0l23" or "ol23" or "o1z3".... etc. It could be done, but holy IF statements Batman! – exceptional exception Jan 19 '15 at 16:14

3 Answers3

2

str_replace()

// Replace "o" with "0"
$numberchar = str_replace("o", "0", trim($_POST['numberchar']));
$categoryparentfilter = "SELECT ID FROM `wp_posts` WHERE `post_title` LIKE '". $numberchar ."%' order by ID desc";
sunshinekitty
  • 2,307
  • 6
  • 19
  • 31
1

You can use MySQL's REPLACE or PHP's str_replace

You can use MySQL's REPLACE function to replace characters in the query itself:

REPLACE('queryStringArgument', 'o', '0')

You can also use PHP's str_replace if you wish to do it on the server:

$numberchar = isset($_POST['numberchar']) ? $_POST['numberchar'] : ""; // Get the POSTed value if it's set.
$fixedNumberchar = str_replace("o", "0", $numberchar);
$categoryparentfilter = "SELECT ID FROM `wp_posts` WHERE `post_title` LIKE '". $fixedNumberchar ."%' order by ID desc";

Note

that you this is probably not such a good idea; you should be catching invalid parameters and notify the user that he's doing something wrong. But that's for you to decide.

Community
  • 1
  • 1
Jonast92
  • 4,964
  • 1
  • 18
  • 32
0

You will want to change this to this:

$categoryparentfilter = "SELECT ID FROM `wp_posts` WHERE REPLACE(`post_title`,'[a-zA-z]+','') LIKE '%".trim(preg_replace("[^0-9]","", $_POST['numberchar']))."%' order by ID desc";

Strips out all characters and only allows numbers, adding the % ad the beginning will allow for the o1234

Danny Broadbent
  • 1,199
  • 1
  • 9
  • 21