0

I have a string like this:

$string = '"Joe Bob" "John Doe" "Amber Page" "Jordan Tole"';

I want to store it in an array with each item in between the " " being an element inside of the array.

e.g.

$Array = StringToArray($string);
2
  • 2
    your current string definition is a syntax error Commented Apr 16, 2012 at 16:23
  • No matter what these answers suggest, don't use explode(): use str_getcsv() php.net/manual/en/function.str-getcsv.php Commented Apr 16, 2012 at 17:22

3 Answers 3

2

Using a combination of PHP's explode function and substr you could use to build an array of the names like this:

$string = '"Joe Bob" "John Doe" "Amber Page" "Jordan Tole"';
$string = substr($string,1,-1);
$names = explode('" "', $string);

This would output the following:

Array
(
    [0] => Joe Bob
    [1] => John Doe
    [2] => Amber Page
    [3] => Jordan Tole
)
Sign up to request clarification or add additional context in comments.

3 Comments

I messed up that String, I forgot to mention that the individual items in the string can have spaces in them, I made the edit above.
I think maybe the space inbetween the quotes is throwing things off, It works kind of if I do explode('"', $string); but if I put the space in between quotes like this: explode('" "', $string) it outputs it all in one element in the array. Is there some special way to specify a space in the explode function? When I do it like this: explode('"', $string); it seperates them but creates a lot of blank elements.
Hmmm, the code I have above works fine. Is what you're testing with different?
1

You can make use of preg_split to pull the string apart:

$string = '"Joe" "John" "Amber" "Jordan"';

$names = preg_split('~(^"|" "|"$)~', $string, 0, PREG_SPLIT_NO_EMPTY);

Result:

array(4) {
  [0]=> string(3) "Joe"
  [1]=> string(4) "John"
  [2]=> string(5) "Amber"
  [3]=> string(6) "Jordan"
}

Comments

0

Pending you correct the string above..

$string = '"Joe" "John" "Amber" "Jordan"';

using explode. <?php $arr = explode('" "', $string); will provide you the following: $arr = array( 0 => '"Joe"', 1 => '"John"'...


However if you meant:

<?php
$string = "Joe John Amber Jordan";
$arr = explode(' ', $string);
// will provide the samething without the " and ".

3 Comments

To get even rid of the quotation marks: $arr = explode('" "', trim($string, '"'));
i updated my answer to include an example for your updated code in your question
For some reason that updated explode isn't working and I can't figure out why. It just stores the entire string in on element in the array instead of separating them.

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.