SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Evangelist bradical1379's Avatar
    Join Date
    Feb 2007
    Posts
    442
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Help with converting a string to an array

    I am trying to convert a string to an array when, however, I want to create multidimensional arrays when the string has items in brackets.

    For example, if the string as passed: (Mary Poppens) Umbrella (Color Yellow)

    I would want to create an array that looks like this:

    Array ( [0] => Array ( [0] => mary [1] => poppens) [1] => umbrella [2] => Array ( [0] => color [1] => yellow) )

    I was able to get the data placed into an array through this:

    PHP Code:
    preg_match_all('/\(([A-Za-z0-9 ]+?)\)/'stripslashes($_GET['q']), $subqueries); 
    But I am having trouble getting the items placed in the multidimensional arrays.

    Any ideas?

  2. #2
    SitePoint Evangelist captainccs's Avatar
    Join Date
    Mar 2004
    Location
    Caracas, Venezuela
    Posts
    514
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by bradical1379 View Post
    But I am having trouble getting the items placed in the multidimensional arrays.

    Any ideas?
    I'm clueless where it comes to regex but this loop does what you asked for:
    PHP Code:
    <?php
    $string 
    "(Mary Poppens) Umbrella (Color Yellow)";
    $op '(';
    $cp ')';

    while (
    strlen($string) > 0) {
        
    $open strpos($string$op);
        if(
    $open !== FALSE) {
            
    $close strpos($string$cp$open);
            if(
    $close !== FALSE) {
                if(
    $open != 0) {
                    
    $x[] = trim(substr($string0$open));
                }
                
    $str trim(substr($string$open$close $open), ' ()');
                
    $x[] = explode (' '$str);
            }
            
    $string trim(substr($string$close+1strlen($string) - $close));
        } else {
            
    $x[] = trim($string);
            
    $string '';
        }
    }
    Denny Schlesinger
    web services


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •