0

I have my tags in line:

word1 word2 word3 "word4 word1" word4 "word7 word4" "word67 word56 word1" word7

need to get everything in array like:

word1
word2
word3
word4 word1
word4
word7 word4
word67 word56 word1
word7

need to do it with explode(" ",$input) and explode("\"",$input) combination, or something else, but i have no idea how..

3 Answers 3

3

I think the best way is to use str_getcsv

Example :

var_dump( str_getcsv('word1 word2 word3 "word4 word1" word4 "word7 word4" "word67 word56 word1" word7', ' ', '"'));
Sign up to request clarification or add additional context in comments.

3 Comments

at the beginning, CSV is only a comma separated value string, in your case the comma is replaced by the space, that's all ;)
@Jay, str_getcsv is meant for parsing CSV rows as a string. Etienne just used it for this application instead. Very clever
I've tested this function in many tag variations, it's perfect what i've been looking for :)
0

If you don't want to go down the preg_split route, you could so explode(" \"", $input), and then go through that output, and where the array item doesn't have a trailing ", split that by space. Where it does have the trailing ", remove it.

It's not an elegant solution, but would work.

$round1 = explode(" \"", $input); // split based on the " at the start
$round2 = array();
foreach ($round1 as $word) {
    if (substr($word,-1) == "\"") {
        $round2[] = str_replace("\"","",$word); // get rid of the trailing "
    }
    else {
      // need to merge our existing array with the exploded array
      $round2 = array_merge($round2, explode(" ", $word);
    }
}

Comments

0

I suggest you to use preg_match_all(). An Example for you

$str = 'word1 word2 word3 "word4 word1" word4 "word7 word4" "word67 word56 word1" word7';
preg_match_all('/(word\d)|("([^"]*)")/', $str, $m);

print '<pre>';
print_r($m[0]);
print '</pre>';

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.