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?

3
  • Instead of .* which is greedy operator, try using .*?, which is lazy. Commented Mar 29, 2012 at 8:19
  • 2
    see here : php.net/manual/en/function.get-defined-functions.php Commented Mar 29, 2012 at 8:19
  • Have fun with $x = functionOne(functionTwo("fgfg")); and all the myriad of similar permutations Commented Mar 29, 2012 at 9:45

3 Answers 3

6

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?

Sign up to request clarification or add additional context in comments.

1 Comment

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.
6

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

Comments

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.

1 Comment

Valid point, invalid argument, PCRE is not regular.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.