Page 1 of 1
how to parse string using preg_split with double quotes
Posted: Thu Mar 17, 2005 7:12 am
by jignesh
Hello
I have problem in parsing String using preg_split,
my problem is that i have one string witch is comma (,) seperated, but it should allow comma(,) between double quotes
for ex. string is
ID, Name, add, City
1, "John Methew", "821, Lodi", "NJ"
now i dont want to split 821, Lodi
please anyone can help me or guide me on this problem.
Posted: Thu Mar 17, 2005 10:02 am
by thomas777neo
First run the string through the str_replace function, replace the " with nothing.
Then you can simply explode the string by the ,.
This will turn it into an array that you can manipulate as you want to.
Posted: Thu Mar 17, 2005 11:18 am
by dakkonz
or perhaps u can replace the "" with something else maybe a - then explode the string after that u will have in an array [1,] [John Methew] [,] [821, Lodi] [, ][NJ] then u can play around with ur array...
Posted: Thu Mar 17, 2005 11:25 am
by thomas777neo
Oops, read the question incorrectly. Thanks for the correction.
Posted: Thu Mar 17, 2005 2:01 pm
by feyd
Code: Select all
<?php
$str = '1, "e;John Methew"e;, "e;821, Lodi"e;, "e;NJ"e;';
echo var_export($str). "e;\n"e;;
preg_match_all('#^\s*(.*?)\s*(?=,)|,\s*(ї"e;\']?)(.*?)\\2\s*(?=,)|\s*,\s*(ї"e;\']?)(.*?)\\4\s*$#m', $str, $matches);
var_export($matches);
?>
Code: Select all
'1, "e;John Methew"e;, "e;821, Lodi"e;, "e;NJ"e;'
array (
0 =>
array (
0 => '1',
1 => ', "e;John Methew"e;',
2 => ', "e;821, Lodi"e;',
3 => ', "e;NJ"e;',
),
1 =>
array (
0 => '1',
1 => '',
2 => '',
3 => '',
),
2 =>
array (
0 => '',
1 => '"e;',
2 => '"e;',
3 => '',
),
3 =>
array (
0 => '',
1 => 'John Methew',
2 => '821, Lodi',
3 => '',
),
4 =>
array (
0 => '',
1 => '',
2 => '',
3 => '"e;',
),
5 =>
array (
0 => '',
1 => '',
2 => '',
3 => 'NJ',
),
)
so, you'll have to combine index 1, 3, and 5 of the returned array using functions such as array_shift(), array_splice() and array_pop().