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

17,770

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);
Share:
17,770
BenMorel
Author by

BenMorel

Author of Brick, a collection of open-source libraries for PHP applications: brick/math : an arbitrary-precision arithmetic library brick/money : a money and currency library brick/date-time : a date and time library brick/phonenumber : a phone number library brick/geo : a GIS geometry library brick/varexporter : a powerful alternative to var_export() ... and a few others.

Updated on June 19, 2022

Comments

  • BenMorel
    BenMorel almost 2 years

    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.

  • Admin
    Admin almost 15 years
    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'";
  • Admin
    Admin almost 15 years
    where the $include is the search term incidentally
  • Muhammad Huzaifa
    Muhammad Huzaifa almost 15 years
    What does the final SQL query look like and what is the SQL error?
  • Admin
    Admin almost 15 years
    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 1 query: SELECT Title, SmallDesc, id, picturesmall FROM recipes WHERE MATCH (Ingredients) AGAINST ('+'pasta','tuna','eggs' -mushrooms' IN BOOLEAN MODE) AND type='0'