Search code examples
phpregexfindphpstormphpdoc

Regex for matching multi-line PHPDoc comments


/**
 * Get Data
 *
 * @param null|ProductInterface $product
 *
 * @return string
 * @throws LocalizedException
 * @throws NoSuchEntityException
 */

I would like to find PHPDoc multi-lines using the regex, such that there isn't an empty line between the PHPDoc @ elements of different types. For example, as between

** @return string
** @throws LocalizedException

as opposed to:

** @param null|ProductInterface $product
**
** @return string

If you're wondered why I need that - I have to add a new empty line between PHPDoc @ elements of different types (@param and @throws in that case).


Solution

  • Something like this could work:

    Regex:

    ^ \* @([a-z]+).*\K(?=\r?\n^ \* @(?!\1))
    
    • ^ \* @([a-z]+).* - capture a PHPDoc line and put whatever is after the @ into capture group \1
    • \K - forget everything we just captured but \1 will remain available
      • \K is specific to PCRE
      • In the replacement I don't want to deal with capture groups so my goal is to assert my position where I want to add the new line
    • (?=\r?\n^ \* @(?!\1)) - ahead of me should be another PHPDoc line and the text after @ is not allowed to be the same as what is stored in \1

    Replacement:

    \n *
    

    https://regex101.com/r/nZpgkF/1

    ^ I modified the test string to have multiple things to split so that you can see how it works.


    If \K is not available in your regex flavor:

    Regex

    (^ \* @([a-z]+).*)(?=\r?\n^ \* @(?!\2))
    

    Replacement:

    $1\n *
    

    https://regex101.com/r/DZ5EKw/1