3

Can anybody help with a valid regex ?

I have a files containing functions like this one

$variable1 = tr ('This was written in % s . ', array ( $year ));

or

tr ('This was written in % s % s . ' ,array ( $month , $year ));

or

tr('some string ')

Strings are always in single quotes.

I need from the text of source which i get with fopen fundtion to extract all strings passed to tr() function. I use php to parse php files. Any help?

UPDATE WOrks:

          $fileContents=file_get_contents($file);              


          preg_match_all("/tr\('(.*?)'/", $fileContents, $matches);

          //preg_match_all('/(?<=tr\s?\(\s?\')(?:\\\\.|[^\\\\\'])*(?=\')/i',        $fileContents, $matches, PREG_PATTERN_ORDER);

exit(json_encode($matches));

2 Answers 2

4

Have you considered using PHP's Tokenizer functions instead of complex regexp?

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

2 Comments

no actually, I think usual regex will do... what would be pros for tokenizer?
For one, you don't need to worry about whitespace (or whether it's single quote or double quote) or whether the result is assiged to a variable or not, or whether there's nested function calls within the arguments. Another argument for using the PHP tokenizer is that it's almost certainly going to be more efficient than PCRE when searching for PHP code... but it all depends why you need this
3

If I understand your question correctly, you want a regex to match strings passed into a function called tr().

The following regex should do:

/tr\('(.*?)'/

So:

<?php
preg_match("/tr\('(.*?)'/", $fileContents, $matches);
print_r($matches);

Comments

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.