Regular Expressions 101

Community Patterns

PHP Class Capture Groups from symbol string for Class, Namespace, Operation (Mutator or Accessor), Target and Method Names

1

Regular Expression
PCRE2 (PHP >=7.3)

/
(?<class>^(?<fully_qualified_class_name>(?<deliniator>(?<!\\)\\(?!\\)(?=(?P>fully_qualified_class_name))){0,1}[A-z_][\w]*)(?=::(?P>method)|$)|^(?<namespace>^(?P>fully_qualified_class_name)*)(?P>deliniator)(?P>fully_qualified_class_name)(?=::(?P>method)|$))(?<scope_resolution_operator>::(?=(?P>method)(?!$)))?(?<method>(?<=::)(?<operation>(?<mutator>[sS]et(?=[A-Z0-1_]|$))|(?<accessor>[gG]et(?=[A-Z0-1_]|$))|(?<condition>[iI]s(?=[A-Z0-1_]|$)|[hH]as(?=[A-Z0-1_]|$)))?_?(?<target>(?<=\w)\w*)|[A-z_]\w*)?$
/
gm

Description

The is helpful for parsing the symbolic reference of a PHP class object for validation or just determining the type and target for the operator. The expression is intended for working with classes and class methods, so the value on the right of the Paamayim Nekudotayim :: will alway be regarded as the method. We are using it with the value returned by class methods and magic constants.

Special assertions are made on the Method name. If the first 3 letters are set or get followed by an underscore or capital letter, its Operation is characterized and captured to the Accessor, Mutator or Condition group. The remainder of the Method name following the underscore will be captured as the Target of the Operation.

Submitted by Jacob Canote - 3 years ago (Last modified 3 years ago)