2

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.

5
  • 2
    $str = 'John','Paul','Ringo','George'; is wrong syntax Commented May 25, 2014 at 8:20
  • And the right one is? Commented May 25, 2014 at 8:21
  • $str = "'John','Paul','Ringo','George'"; ? Commented May 25, 2014 at 8:21
  • Use the users ID for the mysql. Commented May 25, 2014 at 8:22
  • Ok. You mean it's wrong for php. But for MySQL it's right. I wont be echoing it in php, only sending it to the sql statement. Commented May 25, 2014 at 8:23

6 Answers 6

5

If you absolutely don't want to use explode() you could use

$str = 'John,Paul,Ringo,George';
$newStr = "'" . str_replace(",","','", $str) . "'";
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for fastest solution. It's around 2x faster than implode/explode combination.
2

You can use preg_replace with $1 thing.

UPDATED: See usage example:

echo preg_replace('((\\w+)(,?))', '"$1"$2', 'John,Paul,Ringo,George');

Comments

2

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

Comments

1

You can use the explode and implode functions in PHP.

$names = explode(',', 'John,Paul,Ringo,George');
echo implode(',', $names);

2 Comments

I already do, but how do I get 'John', 'Paul' etc. I end up with 'John,Paul'
Your answer needs to be changed to echo implode('\',\'', $names); to get the formatting required.
1

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'

Comments

1
$l = 'John,Paul,Ringo,George';
$lx = "'" . implode("','", explode(",", $l)) . "'";
echo $lx; // 'John','Paul','Ringo','George'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.