-2

If my string is

<?php $str = 'hello world!'; function func_hello($str) { echo $str; }

I want to find the name of any functions in the string

I'm using the code

preg_match_all('%func_.* ?\(%', $c, $matches);

This is a basic example of what I'm doing. In the real world I'm getting results like this

func_check_error($ajax_action_check, array(
func_post('folder') == '/' || func_post(
func_check_error($fvar_ajax_action_check, array(

Whereas I want the result to be

func_check_error(
func_post(
func_check_error(

I've tried \b to set a boundary but it's not working. i.e.

preg_match_all('%\bfunc_.* ?\(\b%', $c, $matches);
Jan
  • 42,290
  • 8
  • 54
  • 79
Daniel Williams
  • 2,195
  • 7
  • 32
  • 53
  • 1
    Do you see the space in your pattern? It should instead be [`func_.*?\(`](https://regex101.com/r/tfd9nY/1/) Additionally, parsing/analyzing code with regular expressions might lead to unexpected results. – Jan Feb 18 '21 at 19:05
  • The space is because there could be a space between the function name and brackets, so the question mark is to make it optional – Daniel Williams Feb 18 '21 at 19:14
  • Something like `func_.*? ?\(` stops the `.*` taking too much. – Nigel Ren Feb 18 '21 at 19:19
  • What is the actual input string? What is the value of `$c`? – BadHorsie Feb 18 '21 at 19:20

2 Answers2

0

The .* capture the opening parenthesis, and then the first parenthesis (after the function name) is captured, because there is the following parenthesis (the one of the array) which correspond to the \( of your pattern.

You should try a more restrictive condition on the function name, such as alphanumeric only or anything but a parenthesis, maybe replace the func_.* by func_[^(]* wich will stop at the first parenthesis match

lycaon
  • 24
  • 2
  • 4
0

Simple regex should work fine:

~func_.*\(~

If this is not giving the results you expect, it may be due to another issue with your code and how you're using the regex.

BadHorsie
  • 14,135
  • 30
  • 117
  • 191