1

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?

Qtax
  • 33,241
  • 9
  • 83
  • 121
jocken
  • 324
  • 3
  • 10

3 Answers3

5

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

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
5

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?

stema
  • 90,351
  • 20
  • 107
  • 135
  • This actually worked, big thank you! But you are all right. Tokenizer would be a better alternative but it didn't find my functions as functions, but as html. – jocken Mar 29 '12 at 12:09
1

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.

Rohan Prabhu
  • 7,180
  • 5
  • 37
  • 71
  • 1
    Valid point, invalid argument, [PCRE is not regular](http://stackoverflow.com/questions/7434272/match-an-bn-cn-e-g-aaabbbccc-using-regular-expressions-pcre). – Qtax Mar 29 '12 at 08:22