Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Mar 2010
    Posts
    235
    Thanks
    39
    Thanked 6 Times in 6 Posts

    preg_match all matches into array

    I want to load all successful matches into an array:

    PHP Code:
    $text="(6-9)+9^2 + (35 + 8) * (2 - 6)/3";
    preg_match('#\((.*)\)#'$text$match); 
    print 
    $match[0] . "<br />"
    The above returns (6-9)+9^2 + (35 + 8) * (2 - 6).

    How do I get an array with
    $match[0]=(6-9)
    $match[1]=(35 + 8)
    $match[2]=(2 - 6)

  • #2
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    http://www.php.net/preg_match_all
    PHP Code:
    preg_match_all'#\(.+\)#U'$text$matches ); 
    The U modifier forces the regexp to be "ungreedy".

    Or:
    PHP Code:
    preg_match_all'#\([^\)]+\)#'$text$matches ); 
    That will match anything starting with an open parenthesis, continuing through anything that is not a close parenthesis, till it finds a close parenthesis.

    Then do a print_r( $matches ); to see what you're able to work with. You'll want to use preg_match_all() to find all matches, as opposed to preg_match(), which will stop searching at the first match.
    Last edited by kbluhm; 04-01-2010 at 04:30 PM.

  • Users who have thanked kbluhm for this post:

    mathceleb (04-16-2010)

  • #3
    Regular Coder
    Join Date
    Mar 2010
    Posts
    235
    Thanks
    39
    Thanked 6 Times in 6 Posts
    Quote Originally Posted by kbluhm View Post
    http://www.php.net/preg_match_all
    PHP Code:
    preg_match_all'#\(.+\)#U'$text$matches ); 
    The U modifier forces the regexp to be "ungreedy".

    Or:
    PHP Code:
    preg_match_all'#\([^\)]+\)#'$text$matches ); 
    That will match anything starting with an open parenthesis, continuing through anything that is not a close parenthesis, till it finds a close parenthesis.

    Then do a print_r( $matches ); to see what you're able to work with. You'll want to use preg_match_all() to find all matches, as opposed to preg_match(), which will stop searching at the first match.
    Fantastic! I used the second code entry you supplied, along with:

    PHP Code:
    echo $match[0][0] . "<br />";
    echo 
    $match[0][1] . "<br />"
    Thanks again!


  •  

    Posting Permissions

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