Search code examples
phpregexpreg-match

PHP preg_match to retrieve text?


I am not good with regular expressions, so I need a little bit of help. I am trying to retrieve text like function inside a string like this:

$str_var = " i do not need this datavar(i need this),  i do not need this datavar(and also this),  and so on";        
preg_match('#\((.*?)\)#', $str_var, $match);
print_r($match)

I would like to have:

arr value 1 = datavar(i need this)
arr value 2 = datavar(and also this)

So far I am able to retrieve the text inside "this is it" and "this is it 2" but I need to retrieve the function name and the content with the pharentesis as well like: "datavar(i need this)" and "datavar(and also this)"

Any ideas


Solution

  • This probably is what you are looking for if the words before the brackets are composed only of letters, as you confirmed in the comments to the question:

    <?php
    $subject = " i do not need this ineedthis(and also this),  i do not need this ineedthistoo(and also this 2),  and so on";
    preg_match_all('#(\w+\([^)]+\))#', $subject, $matches);
    print_r($matches);
    

    The output of above code is:

    Array
    (
        [0] => Array
            (
                [0] => ineedthis(and also this)
                [1] => ineedthistoo(and also this 2)
            )
    
        [1] => Array
            (
                [0] => ineedthis(and also this)
                [1] => ineedthistoo(and also this 2)
            )
    
    )
    

    UPDATE:

    If that word before the brackets is the fixed, literal string datavar, then you can simplify above code to:

    <?php
    $subject = " i do not need this ineedthis(and also this),  i do not need this ineedthistoo(and also this 2),  and so on";
    preg_match_all('#(datavar\([^)]+\))#', $subject, $matches);
    print_r($matches);