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

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.

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

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

Do you have any comma in values?
If not you could use something like:
preg_replace('/[^,]+/g', '\'\1\'', preg_replace('/\'/g', '\\\'', $text))

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

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

Related

PHP adding single quotes to comma separated string

I know I have done this before. I am not sure why I am struggling to do something so simple.
All I am trying to do is add a single quote to a comma separated string.
The php process initially looks like this:
<?php
$checknumber = mysqli_real_escape_string($dbc,trim($_POST['checknumber']));
$splitnumber = preg_replace('/\n$/','',preg_replace('/^\n/','',preg_replace('/[\r\n]+/',"\n",$checknumber )));
$numbers = "'" . implode("', '", $splitnumber ) ."'";
echo $checknumber;
echo $splitnumber;
echo $numbers;
?>
The results look like this:
// $checknumber
AMD111111,AMD222222,AMD333333
// $splitnumber
AMD111111,AMD222222,AMD333333
// $numbers
''
I need the results of $numbers to look like this:
'AMD111111','AMD222222','AMD333333'
The funny thing is I am using a piece of code I've used before that works. So I am at a loss as to why the code is not working here.
The implode() function requires an array as second argument.
It looks like your $splitnumber is just a simple string not an array of strings as it should probably be.
Try splitting your $splitnumber by commas using the explode() function and put the result of that in the implode function.
Should look like that (not tested):
$splitnumber = ...;
$splittedNumbers = explode(",", $splitnumber);
$numbers = "'" . implode("', '", $splittedNumbers) ."'";
There is probably a cleaner solution by just replacing all occurences of , with ','.
Your implode isn't setup correctly.
$numbers = "'" . implode("','", $splitnumber) . "'";

Removing single quotes in PHP

I got some issues trying to INSERT some data from a php document till i got 2 values which contains quotes inside like :
"Rempli d'étoiles"
i d like to remove the ' by a space or even nothing.
-> "Rempli d etoiles"
Here is my what i tried :
$posdeapostrophe = strpos($array, '\'');
if ($posdeapostrophe == false)
{
...
}
else
{
// it goes in this block when it detects a ', but seems like trim doesnt work as i would
$newchaine = trim($array, '\'');
$sql .= "INSERT INTO categorie (id_cat,name_cat) VALUES (" . $cpt . ",'" .$newchaine . "'); ";
thanks!
You can use str_replace().
$array = "Some string's";
$posdeapostrophe = strpos($array, "'");
$val = '';
if ($posdeapostrophe !== false)
{
$val = str_replace("'", "\'", $array);
}
echo $val;
Also can use instead of strpos() and replace() to escape single quotes.
mysqli_real_escape_string($con, $array ); //for mysqli
mysql_real_escape_string($array , $con); //for mysql
What you are currently doing is quite dangerous.
First of all, you should really use the current recommended method for executing queries which is by using PDO: http://php.net/manual/en/book.pdo.php
This will both solve the quotes problem and a massive security hole (SQLi vulnerability) you have currently introduced in your code.
If you still want to replace the single quotes in your text you can indeed do what #scrowler suggested which is:
$your_string = str_replace("'", "", $your_string);
But please use PDO when interacting with a database since this is really the only (safe and recommended) way of doing this.

Add double quote between text seperated by comma [duplicate]

This question already has answers here:
PHP: How can I explode a string by commas, but not wheres the commas are within quotes?
(2 answers)
Closed 8 years ago.
I'm trying to figure out how to add double quote between text which separates by a comma.
e.g. I have a string
$string = "starbucks, KFC, McDonalds";
I would like to convert it to
$string = '"starbucks", "KFC", "McDonalds"';
by passing $string to a function. Thanks!
EDIT: For some people who don't get it...
I ran this code
$result = mysql_query('SELECT * FROM test WHERE id= 1');
$result = mysql_fetch_array($result);
echo ' $result['testing']';
This returns the strings I mentioned above...
Firstly, make your string a proper string as what you've supplied isn't. (pointed out by that cutey Fred -ii-).
$string = 'starbucks, KFC, McDonalds';
$parts = explode(', ', $string);
As you can see the explode sets an array $parts with each name option. And the below foreach loops and adds your " around the names.
$d = array();
foreach ($parts as $name) {
$d[] = '"' . $name . '"';
}
$d Returns:
"starbucks", "KFC", "McDonalds"
probably not the quickest way of doing it, but does do as you requested.
As this.lau_ pointed out, its most definitely a duplicate.
And if you want a simple option, go with felipsmartins answer :-)
It should work like a charm:
$parts = split(', ', 'starbucks, KFC, McDonalds');
echo('"' . join('", "', $parts) . '"');
Note: As it has noticed in the comments (thanks, nodeffect), "split" function has been DEPRECATED as of PHP 5.3.0. Use "explode", instead.
Here is the basic function, without any checks (i.e. $arr should be an array in array_map and implode functions, $str should be a string, not an array in explode function):
function get_quoted_string($str) {
// Here you will get an array of words delimited by comma with space
$arr = explode (', ', $str);
// Wrapping each array element with quotes
$arr = array_map(function($x){ return '"'.$x.'"'; }, $arr);
// Returning string delimited by comma with space
return implode(', ', $arr);
}
Came in my mind a really nasty way to do it. explode() on comma, foreach value, value = '"' . $value . '"';, then run implode(), if you need it as a single value.
And you're sure that's not an array? Because that's weird.
But here's a way to do it, I suppose...
$string = "starbucks, KFC, McDonalds";
// Use str_replace to replace each comma with a comma surrounded by double-quotes.
// And then shove a double-quote on the beginning and end
// Remember to escape your double quotes...
$newstring = "\"".str_replace(", ", "\",\"", $string)."\"";

PHP Convert a string of comma separated values into another format without using a loop

In php, if I had a string of comma separated data like this which came from a database:
John,Paul,Ringo,George
how could I convert it to something like this, without using a for loop or any extra processing. Does php have a function that can do this?
$str = 'John','Paul','Ringo','George';
I currently split the string using explode and then reformat it. Anyway to achieve this without doing that?
The formatted string is sent to a SQL where it's used in a MySQL IN() function.
If you absolutely don't want to use explode() you could use
$str = 'John,Paul,Ringo,George';
$newStr = "'" . str_replace(",","','", $str) . "'";
You can use preg_replace with $1 thing.
UPDATED:
See usage example:
echo preg_replace('((\\w+)(,?))', '"$1"$2', 'John,Paul,Ringo,George');
you can use explode like below
$db_data = 'John,Paul,Ringo,George';//from your db
$l = explode(',',$db_data);
echo "select * from table where column IN('".implode("','",$l)."')";
output:
select * from table where column IN('John','Paul','Ringo','George')
You can use the explode and implode functions in PHP.
$names = explode(',', 'John,Paul,Ringo,George');
echo implode(',', $names);
I hope I got you right:
$str_1 = 'John,Paul,Ringo,George';
$str_2 = explode(',', $str_1);
$str_3 = implode('\',\'', $str_2);
$str_4 = '\''.$str_3.'\'';
echo $str_4;
Output: 'John','Paul','Ringo','George'
$l = 'John,Paul,Ringo,George';
$lx = "'" . implode("','", explode(",", $l)) . "'";
echo $lx; // 'John','Paul','Ringo','George'

How to assign " to a variable in php?

I want to get date using date function but the date should comes between " ". I want to assign " to a variable so that i can get my output by combining the two variables:
$td=""";
$td2="".date("m/d/Y")."";
$td3=""";
$date="$td"."$td2"."$td3";
Please help...?
If you don't want to escape them, just wrap them in a single quote instead:
$td = '"';
$td2 = '"'.date("m/d/Y").'"';
$td3 = '"';
$date = $td.$td2.$td3;
You need to escape them
$td = "\"";
With the backslash, the character is treated as a character by any means necessary and is ignored by php, it wont be used to limiting strings or someting like that.
Try
$td=""";
OR
$td = "\"";
Use backslash or single quotes .
You have to use "\" before " in your $td and $td3 variable.
$td="\"";

Categories