Search code examples
phpregexlaravelpcre

Writing a regex to find translations in a laravel project


I have written a regex pattern:

(trans|trans_choice|Lang::get|Lang::choice|Lang::trans|Lang::transChoice|@lang|@choice)\(([\'"]([a-zA-Z0-9_-]+([.][^)\'"]+?)+)[\'"])(\s?,\s?.*)*?[\)\]];?

For targeting laravel translation strings such as:

trans('email.subject)
@lang('email.confirm-email-address-button')

But I have trouble figuring out how to target translation strings that have slashes in them such as this:

@lang('emails/order-received.edit-order-button')

Solution

  • You may use

    (trans(?:_choice)?|Lang::(?:get|choice|trans(?:Choice)?)|@(?:lang|choice))\(([\'"]([^\'"]+)[\'"])[)\]];?
    

    See the regex demo.

    Details

    • (trans(?:_choice)?|Lang::(?:get|choice|trans(?:Choice)?)|@(?:lang|choice)) - Group 1:
      • trans(?:_choice)? - trans followed optionally with _choice
      • | - or
      • Lang::(?:get|choice|trans(?:Choice)?) - Lang:: followed with get, choice, trans or transChoice
      • | - or
      • @(?:lang|choice) - @ followed with lang or choice
    • \( - a ( char
    • ([\'"]([^\'"]+)[\'"]) - Group 2: ' or ", then Group 3 matching any 1+ chars other than ' and " and then " or '
    • [)\]] - a ) or ] char
    • ;? - an optional ;.

    NOTE: Parsing code with one regex might be too fragile. Please consider using this regex in a more complex solution or using a dedicated parser if any exists.