Search code examples
phppreg-match-alltext-extraction

Get all substrings between parentheses


I want to extract all strings between two characters (parentheses).

$string = "blah blah blah (blorp) blah blah (bloop) blah blah (bam)";

Desired output:

['blorp', 'bloop', 'bam']

I don't need any of the blah blahs, just everything within parenthesis.


Solution

  • You can do this with a regular expression:

    $string = "blah blah blah (blorp) blah blah (bloop) blah blah (bam)";
    preg_match_all("/\((.*?)\)/", $string, $result_array);
    
    print_r( $result_array[1] ); // $result_array[0] contains the matches with the parens
    

    This would output:

    Array
    (
        [0] => blorp
        [1] => bloop
        [2] => bam
    )
    

    My regular expression uses a non-greedy selector: (.*?) which means it will grab as "little" as possible. This keeps it from eating up all the ) and grabbing everything between the opening ( and the closing ) how ever many words away.