2

in my php code I run a bunch of shell scripts that finally output the following

['October 20, 2003', '047085815X', '978-\n0470858158', '1', u'\nWireless Foresight: Scenarios of the Mobile World in 2015 [Hardcover]\n']

the above output is saved to $temp.

However, when I do echo $temp[0] it prints the first open bracket and echo $temp[1] print the single quote mark etc.....

I believe this is because its a string and not an array.

I would like to convert this to n array were each element is separated with a coma.

However, note that october 20, 2003 has a comma in it and that should remain its own element.

Can someone point me to what function im looking for.

2
  • What is the u before the string in array position 4? Commented Oct 11, 2012 at 9:02
  • Have a look at str_getcsv in the php manual nz1.php.net/str_getcsv Commented Oct 11, 2012 at 9:05

4 Answers 4

2

trim the opening and closing [], then use str_getcsv()

Sign up to request clarification or add additional context in comments.

1 Comment

Welp.. much better than mine; +1.
1

I think this is the function you're looking for

str_getcsv()

quick example

$line = "'October 20, 2003', '047085815X', '978-\n0470858158', '1', '\nWireless     Foresight: Scenarios of the Mobile World in 2015 [Hardcover]\n'";

$parsed = str_getcsv(
  $line, # Input line
  ",",   # Delimiter
  "'"   # Enclosure
);

print_r($parsed);

output:

Array ( [0] => October 20, 2003 [1] => 047085815X [2] => 978- 0470858158 [3] => 1 [4] => Wireless Foresight: Scenarios of the Mobile World in 2015 [Hardcover] ) 

Comments

0

What you have appears to be closer to a javascript array. I don't know how your shell script works, but I do know how php arrays are formed; you need the following to form a php array:

$temp = array('item1','item2','etc');

So for you, I'd output the following, minus the square brackets:

$temp = array('October 20, 2003', '047085815X', '978-\n0470858158', '1', '\nWireless Foresight: Scenarios of the Mobile World in 2015 [Hardcover]\n');

And then $temp[0] will return the correct information.

Comments

0

Your input looks very much like a js array, except for the mysterious u symbol staying outside of the single quotes, which every other answer seems to ignore. So will I. If you change your single quotes to double quotes, you'll be able to use json_decode function to get a php array from the js one.

$str = '["October 20, 2003", "047085815X", "978-\n0470858158", "1", "\nWireless Foresight: Scenarios of the Mobile World in 2015 [Hardcover]\n"]';
print_r(json_decode($str));

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.