Frage

I'm trying to extract words (read: functions) from a string with RegExp and pass them to a PHP function.

The following works pretty well already:

$func = preg_replace("/(\b.+\b)/Ue", 'extract_functions(\'\\1\')', $oneliner);

While it extracts existing functions from the string it also extracts variables with the same name, but without the starting $ char.

So if the string contains an existing function named get_function it also extracts a variable named $get_function but without the starting $, so I can't be sure whether I have a function or variable extracted.

My idea was to exclude words starting with $ but that doesn't seem to work:

$func = preg_replace("/[(\b[^\$].+\b)/Ue", 'extract_functions(\'\\1\')', $oneliner);

I'm out of ideas...

War es hilfreich?

Lösung 2

Thanks to Jeff, here's the solution that works for me:

$filecontent = file_get_contents($file); // Parsing the file's contents into a string
$re = '/(?<!\$)(\b\S+?\b)(?=\()/'; // The pattern
preg_match_all($re, $filecontent, $out, PREG_PATTERN_ORDER);

print_r($out[0]);

I'm using a negative lookbehind as suggested by Jeff as well as a positive lookahead checking for a ( after each word, but without making the ( part of the match.

I went for the ( part as that defines a PHP function as far as I'm concerned.

I'm open for improvements! :-) Thanks to Jeff!

Andere Tipps

You can use a negative lookbehind to make sure that there's no $ preceding your function/variable:

$func = preg_replace("/(?<!\$)(\b.+\b)/Ue", 'extract_functions(\'\\1\')', $line);

By the way [(\b[^\$] is a bit wrongly formed. You have a character class containing (, \b, ^ and $, which doesn't work. It will actually match any of those characters instead of not matching a $ character.

It would have been a little closer with /[^$](\b.+\b)/ but this one might not work at the beginning of strings.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top