jocken
jocken

Reputation: 324

Regex to find function call php

I need the regex to find function calls in strings in php, I have tried to search here on stackoverflow but none of the ones i've tried worked.

this pattern: ^.*([\w][\(].*[\)])

This will match: functionone(fgfg) but also functionone(fgfg) dhgfghfgh functiontwo() as one match. Not 2 separate matches (as in functionone(fgfg) and functiontwo().

I don't know how to write it but I think this is what I need.
1. Any string, followed by (
2. Any string followed by )

And then it should stop, not continue. Any regex-gurus that can help me out?

Upvotes: 1

Views: 4357

Answers (3)

stema
stema

Reputation: 92986

I see 5 issues with your regex

  1. If you want to match 2 functions in the same row, don't use the anchor ^, this will anchor the regex to the start of the string.

  2. You then don't need .* at the start maybe more something like \w+ (I am not sure what the spec of a function name in PHP is)

  3. if there is only one entry in a character class (and its not a negated one), you don't need the character class

  4. The quantifier between the brackets needs to be a lazy one (followed by a ?). So after this 4 points your regex would look something like

    \w+\(.*?\)
    
  5. Is a regex really the right tool for this job?

Upvotes: 6

Rohan Prabhu
Rohan Prabhu

Reputation: 7302

A function signature is not a regular language. As such, you cannot use a regular expression to match a function signature. Your current regex will match signatures that are NOT valid function signatures.

What I would suggest you use is the PHP tokenizer.

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212412

Don't use regexp for this... use PHP's built-in tokenizer

Upvotes: 6

Related Questions