BlackPage
BlackPage

Reputation: 107

PHP Regexp with variable in string to search

I'm in need of a regexp that will allow me to retrieve all the following data from a php source file :

MUI('Some text')
MUI("Some text", $lang)

The regexp is used to extract all the terms enclosed in MUI("...") in a php file in order to build a list of items to translate. I already have the regexp for the first case :

MUI("Some text") > $pattern = '/MUI\((["\'].*?)["\']\)/';

But I had to add a parameter which is a variable and since then my regexp wont find the second case

MUI("Some text", $lang).

Please be aware that the text to find may be enclosed by ' or ". Thanks in advance for your ideas.

Upvotes: 1

Views: 54

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You can use

(?s)MUI\((?|"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)')

See the regex demo.

Details:

  • (?s) - . now matches any chars including line break chars
  • MUI\( - MUI( string
  • (?|"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)') - Branch reset group matching either:
    • "([^"\\]*(?:\\.[^"\\]*)*)" - a double quote string literal (capturing what is in between quotes into Group 1)
    • | - or
    • '([^'\\]*(?:\\.[^'\\]*)*)' - a single quote string literal (capturing what is in between quotes into Group 1 - yes, still Group 1 since this is an alternative inside a branch reset group).

Upvotes: 1

Related Questions