Tutorial :Add quotes to values in a string separated by a comma php



Question:

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.


Solution:1

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) . "'";  


Solution:2

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);  


Solution:3

Do you have any comma in values?

If not you could use something like:

preg_replace('/[^,]+/g', '\'\1\'', preg_replace('/\'/g', '\\\'', $text))  


Solution:4

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


Solution:5

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »