pull_stack_developer
pull_stack_developer

Reputation: 21

How to find particular pattern using regex?

I have some .php files in a directory that calls a user defined function:

_l($string);

each time different string is passed to that function and all strings are static, (i.e. not a single string is entered by user input).

Now I want a script that can list down all the strings form all the files of that directory, which are passed into _l($string); I had tried:

 $fp = fopen($file, "r");
    while(!feof($fp)) {
      $content .= fgets($fp, filesize($file));
      if(preg_match_all('/(_l\(\'.*?\'\);)/', fgets($fp, filesize($file)), $matches)){
         foreach ($matches as $key => $value) {
           array_push($text, $value[0]);
         }
      }
   }

I get strings but not every strings those are in files, some strings are not match with given regex, so what are the condiotion that is required to get all the strings?

Upvotes: 1

Views: 102

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 79014

This is easier to get strings in double " or single ' quotes as the _l() function argument.

$string = file_get_contents($file);
preg_match_all('/_l\([\'"](.*?)[\'"]\);/', $string, $matches);
$text = $matches[1];

If needed you can add some optional spaces before and after the ( and before the ):

'/_l\s*\(\s*[\'"](.*?)[\'"]\s*\);/'

Also, if the function can be used in a loop or if or something where it's not terminated by a semi-colon ; then remove it from the pattern.

Upvotes: 1

Related Questions