-2

I have a variable with string value of 'laptop,Bag' and I want it to look like ' "laptop","Bag" 'or "laptop","Bag". How could I do this one? Is there any php function that could get this job done? Any help please.

Eli
  • 1,166
  • 3
  • 22
  • 54

7 Answers7

4

This would work. It first, explodes the string into an array. And then implodes it with speech marks & finishes up by adding the opening & closing speech mark.

$string = "laptop,bag";
$explode = explode(",", $string);
$implode = '"'.implode('","', $explode).'"';

echo $implode;

Output: 
"laptop","bag"
Dave Clarke
  • 2,607
  • 4
  • 18
  • 35
4

That's what str_replace is for:

$result = '"'.str_replace(',', '","', $str).'"';
Joseph Silber
  • 193,614
  • 53
  • 339
  • 276
  • Need to add the " at the start & end of string. – Dave Clarke Feb 21 '14 at 15:45
  • I agree that this would be the more simple method of creating the string. No need to explode or implode anything, and no need to create another function. – Joe Feb 21 '14 at 15:48
2

This would be very easy to do.

$string = 'laptop,bag';
$items = explode(',', $string);
$newString = '"'.implode('","', $items).'"';

That should turn 'laptop,bag' into "laptop","bag".

Wrapping that in a function would be as simple as this:

function changeString($string) {
    $items = explode(',', $string);
    $newString = '"'.implode('","', $items).'"';
    return $newString;
}
Joe
  • 1,294
  • 10
  • 17
1

I think you can explode your string as array and loop throw it creating your new string

function create_string($string)
{
    $string_array = explode(",", $string);
    $new_string = '';
    foreach($string_array as $str)
    {
        $new_string .= '"'.$str.'",';
    }
    $new_string = substr($new_string,-1);

    return $new_string;
 }

Now you simply pass your string the function

$string = 'laptop,Bag';
echo create_string($string); 
//output "laptop","Bag"
Fabio
  • 21,516
  • 12
  • 49
  • 63
1

For your specific example, this code would do the trick:

<?php
$string = 'laptop,bag';
$new_string = ' "' . str_replace(',', '","', $string) . '" ';
// $new_string: "laptop","bag"
?>

That code would also work if you had more items in that list, as long as they are comma-separated.

Patito
  • 317
  • 3
  • 11
1

Use preg_replace():

$input_lines="laptop,bag";
echo preg_replace("/(\w+)/", '"$1"', $input_lines);

Output:

'"laptop","Bag"'
Amal Murali
  • 70,371
  • 17
  • 120
  • 139
Nambi
  • 11,454
  • 3
  • 34
  • 49
0

I think you can perform that using explode in php converting that string in to an array.

$tags  = "laptop,bag";
$tagsArray = explode(",", $tags);
echo $tagsArray[0]; // laptop
echo $tagsArray[1]; // bag

Reference http://us2.php.net/manual/en/function.explode.php

related post take a look maybe could solve your problem.

How can I split a comma delimited string into an array in PHP?

Community
  • 1
  • 1
diegochavez
  • 633
  • 8
  • 13