#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2004
    Posts
    87
    Rep Power
    62

    Explode with regex


    Hi All

    I'm hopeless/intellectually lazy with regex.

    I need to turn a string like this . . .

    'one, two, three, (four, five), six'

    . . . into an array like this . . .

    [0] => 'one'
    [1] => 'two'
    [2] => 'three'
    [3] => '(four, five)'
    [4] => 'six'

    . . . so basically explode the string by ',' delimiter except where the ',' delimiter is inside brackets.

    Appreciate any help.
    Last edited by mattzo; June 14th, 2013 at 05:01 PM.
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1046
    PHP Code:
    <?php

    $list 
    'one, two, three, (four, five), six';

    preg_match_all('/(?<=^ |, )(?:\([^)]*\)|[^,]*)/'$list$elements);
    var_dump($elements[0]);
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2004
    Posts
    87
    Rep Power
    62
    Thanks so much! That's nearly perfect - except the array contains only four values - the first one ('one') is missing.

    I suppose I could add a dummy value to the front of the string - but is there a 'cleaner' way to do it?
  6. #4
  7. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1046
    Remove the stray space after the caret.

    Comments on this post

    • mattzo agrees
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2004
    Posts
    87
    Rep Power
    62
    perfect, thanks again

IMN logo majestic logo threadwatch logo seochat tools logo