Wil
Wil

Reputation: 892

Regular expression to change user input

I am doing a search on my database. If the user enters eg. "foo bar" I want to display rows that have both "foo" AND "bar".

My SQL syntax looks like this: SELECT * FROM t1 WHERE MATCH (t1.foo_desc, t2.bar_desc) AGAINST ('+foo* +bar*')

How can I change the user input "foo bar" into "+foo* +bar*" using a regular expression in PHP?

Upvotes: 0

Views: 285

Answers (4)

Gumbo
Gumbo

Reputation: 655239

I would use a regular expression to replace the spaces between two words by * +:

'+' . preg_replace('/\s+/', '* +', trim($input)) . '*'

Edit   Basically this is an implementation to what Tomalak said just with \s instead of \W.

Upvotes: 0

Greg
Greg

Reputation: 321628

$match = '+' . implode('* +', explode(' ', $input)) . '*';

This assumes that the input isn't an empty string;

Edit: As @Bart S points out, str_replace (or mb_str_replace if you're dealing with multibyte characters) would be even simpler...

$match = '+' . str_replace(' ', '* +', $input) . '*';

Upvotes: 2

Tomalak
Tomalak

Reputation: 338188

First, trim the user input and remove anything strange (punctuation, quotes, basically everything "\W", except white space of course).

Then, substitute:

(?<=\w)\b

with

"*"

and:

\b(?=\w)

with

"+"

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272257

You should use \b and \B to identify the word/not-word boundaries, and thus insert your +/*.

Upvotes: 1

Related Questions