Help splitting strings

Discussion in 'PHP' started by YourChild, Oct 3, 2008.

  1. #1
    Say I have a string like this:

    
    $string = 'Micheal, Smith, 31, "Corona, California", dentist';
    
    Code (markup):
    I want to split this string so that I have an array like this:

    
    $myarray[0] = 'Michael';
    $myarray[1] = 'Smith';
    $myarray[2] = 21;
    $myarray[3] = 'Corona, California';
    $myarray[4] = 'dentist';
    
    How do I go about doing this?
    
    if I do:
    
    $myarray= explode(",", $string);
    
    I will get this:
    
    $myarray[0] = 'Michael';
    $myarray[1] = 'Smith';
    $myarray[2] = 21;
    $myarray[3] = '[COLOR="Red"]"[/COLOR]Corona'; 
    $myarray[4] = 'California[COLOR="Red"]"[/COLOR]';
    $myarray[5] = 'dentist';
    
    
    Code (markup):
    ANy help will be gladly appreciated! Thanks!
     
    YourChild, Oct 3, 2008 IP
  2. keyaa

    keyaa Peon

    Messages:
    137
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    0
    #2
    There you go:
    $myarray = preg_split( "/[\s,]*\\\"([^\\\"]+)\\\"[\s,]*|[\s,]+/", $string, 0, PREG_SPLIT_DELIM_CAPTURE );
    PHP:
    hth
     
    keyaa, Oct 3, 2008 IP
  3. Sillysoft

    Sillysoft Active Member

    Messages:
    177
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    58
    #3
    Yes, much better!
     
    Sillysoft, Oct 3, 2008 IP