how to parse string using preg_split with double quotes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jignesh
Forum Newbie
Posts: 4
Joined: Thu Mar 17, 2005 7:06 am

how to parse string using preg_split with double quotes

Post 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.
User avatar
thomas777neo
Forum Contributor
Posts: 214
Joined: Mon Mar 10, 2003 6:12 am
Location: Johannesburg,South Africa

Post 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.
dakkonz
Forum Commoner
Posts: 69
Joined: Sat Dec 27, 2003 2:55 am
Location: Asia

Post 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...
User avatar
thomas777neo
Forum Contributor
Posts: 214
Joined: Mon Mar 10, 2003 6:12 am
Location: Johannesburg,South Africa

Post by thomas777neo »

Oops, read the question incorrectly. Thanks for the correction.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

<?php

	$str = '1, &quote;John Methew&quote;, &quote;821, Lodi&quote;, &quote;NJ&quote;';
	
	echo var_export($str). &quote;\n&quote;;
	
	preg_match_all('#^\s*(.*?)\s*(?=,)|,\s*(ї&quote;\']?)(.*?)\\2\s*(?=,)|\s*,\s*(ї&quote;\']?)(.*?)\\4\s*$#m', $str, $matches);
	
	var_export($matches);

?>

Code: Select all

'1, &quote;John Methew&quote;, &quote;821, Lodi&quote;, &quote;NJ&quote;'
array (
  0 =>
  array (
    0 => '1',
    1 => ', &quote;John Methew&quote;',
    2 => ', &quote;821, Lodi&quote;',
    3 => ', &quote;NJ&quote;',
  ),
  1 =>
  array (
    0 => '1',
    1 => '',
    2 => '',
    3 => '',
  ),
  2 =>
  array (
    0 => '',
    1 => '&quote;',
    2 => '&quote;',
    3 => '',
  ),
  3 =>
  array (
    0 => '',
    1 => 'John Methew',
    2 => '821, Lodi',
    3 => '',
  ),
  4 =>
  array (
    0 => '',
    1 => '',
    2 => '',
    3 => '&quote;',
  ),
  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().
Post Reply