-1

I have a string that looks like this:

'word','another word','and a sentence','and more','etc etc'

I need to split this into two strings, divided by the second comma -- which shouldn't show in either of the sentences. What complicates things is that here can also be commas inside the various quotes parts of the string.

3
  • 3
    Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer! Commented Apr 10, 2013 at 6:06
  • is this complete an array or string ? Commented Apr 10, 2013 at 6:07
  • @Phil You will want to double check your accepted answer. Commented Apr 10, 2013 at 8:54

5 Answers 5

1

This very much looks like CSV syntax, so:

$parsed  = str_getcsv($string, ',', "'");
$string1 = join(',', array_slice($parsed, 0, 2));
$string2 = join(',', array_slice($parsed, 2));

If your PHP version is below 5.3 and hence you don't have str_getcsv, you can replicate this using a virtual file handle to php://temp and fgetcsv.

Alternatively, depending on how difficult your syntax is, strtok can be used for a simple parser. Find the first ', then the next ', then a ,, then a ', then the next ' and you have the first part of the string...

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

2 Comments

deceze, is there a way for me to keep the quotes around the various parts of the string? str_getcsv strips them all out.
Then just put them back. array_map(function ($str) { return "'$str'"; }, $parsed);
0
$a="'word','another word','and a sentence','and more','etc etc'";

//preg_match('{(.*?,[^,]*),(.*)}', $a, $matches);
preg_match('{(.*?[^\\\\]\',.*?[^\\\\]\'),(.*)}', $a, $matches); //UPDATE 
print_r($matches);

DISPLAY:

    Array
(
    [0] => 'word','another word','and a sentence','and more','etc etc'
    [1] => 'word','another word'
    [2] => 'and a sentence','and more','etc etc'
)

3 Comments

"What complicates things is that here can also be commas inside the various quotes parts of the string." - This solution fails if there is a comma in a string.
yes,if group1 or 2 hv comma ,it fails , i post another solution below use eval("\$arr = array($a);");
UPDATE TO preg_match('{(.*?[^\\\]\',.*?[^\\\]\'),(.*)}', $a, $matches); , or \'
0

Since you are saying that there can be commas in between quotes .. so preg_split can help you much better than explode

        <?php

                 $string = "'word','another word','and a sentence','and more','etc etc'";
                 $pattern = '%\',\'%';
                 $split = preg_split($pattern,$string);
                 $array1 = array();
                 $array2 = array();
                 foreach($split as $key=>$value)
                 {
                    $value  = trim($value,"'");
                    $value = "'{$value}'";

                    if(($key === 0) || ($key ===1))
                    {
                        $array1[] = $value;
                    }
                    else
                    {
                        $array2[] = $value; 
                    }
                 }

                echo $req_string1 = implode(',',$array1);
                echo "<br>";
                echo $req_string2 = implode(',',$array2);     


             ?>

Comments

0

commas in between quotes

$a="'word','another word','and a sentence','and more','etc etc'";

eval("\$arr =  array($a);");

$text1='';
$text2='';
foreach($arr AS $k=>$v){
    if($k<2){
        $text1.=$text1?',':'';
        $text1.="'{$v}'";
    }else{
        $text2.=$text2?',':'';
        $text2.="'{$v}'";
    }
}
echo $text1;
echo PHP_EOL;
echo $text2;

'word','another word'

'and a sentence','and more','etc etc'

Comments

0

For those who do not have a bias against regex, preg_split() can achieve the desired result in one concise call.

Match two repetitions of single-quoted substrings followed by a comma. \K is used to restart the fullstring match -- therefore consuming the unwanted comma between the two halves.

Code: (Demo)

$csv = "'word','another word','and a sentence','and more','etc etc'";
print_r(
    preg_split("/^(?:'[^']*'\K,){2}/", $csv)
);

Output:

Array
(
    [0] => 'word','another word'
    [1] => 'and a sentence','and more','etc etc'
)

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.