Search code examples
regexregex-groupphpdoc

Regex for splitting PHPDoc priperties


I got this very specific regex asignment and haven't been able to get it right. The rules are:

Full match - each line of PHPDoc containing a valid property
(valid = starts with @property/@property-read, has name and type)
Group 1 - property/property-read
Group 2 - type, can contain type|NULL
Group 3 - name, can contain name -> otherName
Group 4 (optional) - comment, can contain multiple words, numbers or other characters

This is the closest I got:

(?m)@(\S+) (\S+) (\S+(?: -> \S+)*) ?(.*)(?:\*\/)?

It kinda works but there's a problem when the end of PHPDoc is on the same line as the last property - it makes it part of group 4. Now I'm not sure who would actually write it that way but I was told to fix it and I don't know how.

Test string:

/**
 * Class Object
 * @package Model\Example\Objects
 * @property-read int id
 * @property order_id
 * @property string|NULL external_order_id -> externalOrderId
 * @property string order_source
 * @property int order_source_id
 * @property string order_source_info foo, foo, bar.
 * @property int order_status_id
 * @property int date_add
 * @property int date_confirmed
 * @property int date_in_status
 * @property string user_login
 * @property string phone
 * @property string email
 * @property array products 21 foobar*/

Solution

  • You can try this.

    @(\S+) (\S+) (\S+(?: -> \S+)*) ?((?:(?!\*\/).)*)

    This is a demo.