2

this is my string, and I want it to convert into 2D Array.

[email protected];"Hi ;John";man;405089;

[email protected];Hi Sarah;woman;405089;

And I want to create array from this. I fount this code:

$ret = array_map (
  function ($_) {return explode (',', $_);},
  explode (';', $data)
);

Therefore instead of ',' would be ';' and instead of ';' would be '\n', right?

But It doesn't work correctly yet. If you look once more, there is "Hi ; John"..

I want make this code to ignore everything inside of " ", because there is a semicolon.

3
  • Firstly try to split string properly. Then thin about building an array. Commented Oct 30, 2015 at 9:02
  • And what is your expected output Commented Oct 30, 2015 at 9:04
  • 3
    That looks like it could be parsed by CSV-handling functions, specifying ; as the field separator. Commented Oct 30, 2015 at 9:05

2 Answers 2

4

First remove characters between and including ", then run your function. Here is a one line code to remove "Hi ; John" from your string:

$result = preg_replace('/\".*?\"/', '', $subject);
  • \" matches the character " literally
  • .*? matches any character (except newline), Quantifier: *? Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
  • \" matches the character " literally
Sign up to request clarification or add additional context in comments.

Comments

4

Instead of explode, take a look at str_getcsv.

This will handle your case with the semicolon inside the quotes if you specify a delimiter, like so.

str_getcsv($_, ';')

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.