Search code examples
phpregexpreg-matchphpdocnegative-lookbehind

preg_match negative lookbehind


I'm trying to parse PHPDoc tags with preg_match, but I'm having some issue with negative lookbehind. I've never used those before, but it is my understanding that they're used as exclusions.

Here is my pattern:

/\*\*.+?(?<! \*/)@access public.+? \*/\s+?function\s+[a-zA-Z0-9_]+\(

Here is my sample PHP file I'm trying to parse:

<?php

/**
 * This is the shortcut to DIRECTORY_SEPARATOR
 */
defined('DS') or define('DS',DIRECTORY_SEPARATOR);

/**
 * Foo
 * 
 * @return bool
 * @access public
 */
function foo()
{
    return true;
}

I want to match any function with an @access public tag, but in this case the match starts at the DS constant's comment. I thought the (?<! \*/) would exclude it matching the closing comment tag of the DS comment.

What am I missing?


Solution

  • Following the link by @bishop, I found an example using negative lookahead that works for me.

    I changed

    .+?(?<! \*/)

    to

    (?:(?! \*/).)+?

    So the full pattern is now:

    /\*\*(?:(?! \*/).)+?@access public.+? \*/\s+?function\s+[a-zA-Z0-9_]+\(

    EDIT:

    Full pattern that also matches function types and parameters:

    (?<full>[\t ]*?/\*\*(?:(?! \*/).)+?@access public(?:(?! \*/).)+? \*/\s+?(?:public |protected |private )??(?:static )??function\s+[a-zA-Z0-9_]+\(.*?\))

    And class matching:

    (?<full>(?<indent>[\t ]*?)/\*\*(?:(?! \*/).)+?@access public.+? \*/\s+?(?:abstract )??class\s+[a-zA-Z0-9_]+\s??.*?{)