views:

1690

answers:

6

I have a search box that can contain multiple values using a comma, eg Pasta, tuna, eggs

Im using FULLTEXT mysql search but I need to use some kind of preg_replace to turn Pasta, tuna, eggs into 'Pasta','tuna','eggs'

If I enter this 'Pasta','tuna','eggs' into the search box the results are correct.

Thanks people

A: 

Do you have any comma in values?

If not you could use something like:

preg_replace('/[^,]+/g', '\'\1\'', preg_replace('/\'/g', '\\\'', $text))
Paulo Santos
A: 

implode your string, then foreach resulting array and add needed symbols

michas
+1  A: 

Are you building an SQL query with the list? If so, you should take some time to make sure the resulting SQL is properly escaped as well.

$myList = "pasta, tuna, eggs";

$items = preg_split("/[,\\s]+/", $myList);
$sqlItems = array();
foreach ($items as $item) {
    $sqlItems[] = "'" . mysql_real_escape_string($item) . "'";
}

// Add new list to SQL
$sql .= implode(",", $sqlItems);
Blixt
This is defienetly a step in the right direction as the string appears to be correct, I get a MYSQL error however with this search:$query_finder = "SELECT Title, SmallDesc, id, picturesmall FROM recipes WHERE MATCH (Ingredients) AGAINST ('+$include -$exclude' IN BOOLEAN MODE) AND type='$type'";
where the $include is the search term incidentally
What does the final SQL query look like and what is the SQL error?
Blixt
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'pasta','tuna','eggs' -mushrooms' IN BOOLEAN MODE) AND type='0' LIMIT 0, 10' at line 1query: SELECT Title, SmallDesc, id, picturesmall FROM recipes WHERE MATCH (Ingredients) AGAINST ('+'pasta','tuna','eggs' -mushrooms' IN BOOLEAN MODE) AND type='0'
+1  A: 

Don't use regular expressions for problems that can be solved otherwise. What you want is a simple string replacement:

$string = "'" . str_replace(",", "','", $string) . "'";

You should escape quotes inside the string first, though (don't know what your escape character is, assuming it's backslash):

$string = "'" . str_replace(array("'", ","), array("\\'", "','"), $string) . "'";
soulmerge
simple and works!
Scott
A: 

Guys sorry for the trouble but I've solved my own question! Ive looked at this and it was all wrong to begin with.

I had to replace each , with a space and a plus sign so ", tuna" = " +tuna"

Thanks anyway

A: 

Thanks a lot, your questions solves my problems.

Thanks Arya

This answer-comment is unnecessary. In future, answer questions, get upvoted then come back and comment or upvote the question.
random