Question

I have this string:

$str = 'Small ship in the sea';

I'd like to have this output:

"Small ship in the sea"

How can I accomplish this in PHP?

Thanks in advance

EDIT: The answers provided are pretty obvious. I wanted to provide a simple example, what I'm actually doing is loading a huge text file and each line is stored in multiple arrays. So each array should have the quotes at the end and at the beginning, so what would be a solution to the example provided before? Maybe using regex to add the quotes?

EDIT 2:

Apologies for the confusion this is my code:

$users = file('xls/try_traffic.txt'); //Load File

$users = preg_replace('/, TG=\d{3}/', '', $users);

$users = str_replace("LABEL=", "", $users);

$users = str_replace('"', "", $users);

$users = preg_replace("/\t/", '","', $users);

print_r($users);

I get this output (the simple version):

Array ( [0] => 01/16/2014 00:00:00","30","TLAGMSC1-MSX","TMXCABINLC

[1] => 01/16/2014 00:00:00","30","TLAGMSC1-MSX","TMXLPZOGMV

[2] => 01/16/2014 00:00:00","30","TLAGMSC1-MSX","TMXLPZ2WLD1

)

So I want to add the quotes at the beginning and end of each, so it looks like this:

Array ( [0] => "01/16/2014 00:00:00","30","TLAGMSC1-MSX","TMXCABINLC"

[1] => "01/16/2014 00:00:00","30","TLAGMSC1-MSX","TMXLPZOGMV"

[2] => "01/16/2014 00:00:00","30","TLAGMSC1-MSX","TMXLPZ2WLD1"

)

Was it helpful?

Solution 2

I think this is what you want: EDIT 5

foreach ($users as $k => $v) {
    $users[$k] = (substr($v, 0, 1) == '"') ? ($v) : ('"'. $v);
    $users[$k] = (substr($v, strlen($v) -1) == '"') ? ($v) : ($v .'"');
}
print_r($users);

Check out PHP String Documentation for more details on how to deal with strings in PHP.

Personally, I use single quotes all the time, and only when absolutely necessary do I use doublequotes. It's much easier to predict string behavior with that approach IMO. Hope this helps!

OTHER TIPS

Why not just make use of the concatenation . operator ?

<?php
$str = 'Small ship in the sea';
echo '"'.$str.'"'; //"prints" "Small ship in the sea"

The answers provided are pretty obvious. I wanted to put a simple example, what I'm actually doing is loading a huge text file and each line is stored in multiple arrays. So each array should have the quotes at the end and at the beginning.

The code

<?php
$arr = file('yourtextfile.txt');
$new_arr = array_map('addquote',$arr);

function addquote($v)
{
return '"'.$v.'"';
}

print_r($new_arr);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top