简体   繁体   中英

Regex match string starting with dollar sign and contains ( and no spaces or hyphen

Trying to get a regex that matches

$hey()

$hey('hi')

But not:

$hey->hi()

$hey moretext()

Needs to start with a dollar sign and have a ( and no spaces or dashes.

My idea was:

^\$.*\[^- ]$

Basically trying to find all the variable functions in my PHP code base.

This should do the job.

\w+ will match all valid variable names, ( and ) are required. Anything (or nothing) is allowed between the ().

^\$\w+\(.*\)

PHP has a built-in lexer that is better (more accurate) than any regexp:

$tokens = token_get_all('<?php $var; $bar("hi"); $tar->(123);');

foreach ($tokens as $index => $token)
{
    $token_next = $tokens[$index + 1] ?? null;

    if (is_array($token) and $token[0] === T_VARIABLE and $token_next === '(')
    {
        var_dump($token[1] . $token_next);
    }
}

Keep in mind that you are wrong about the pattern since these lines are valid PHP code:

  1. $var ();
  2. $var\n\n();
  3. ${' aaaaaa'}\n\n();
  4. ${" aaaaaa$bar->bbbbbb"}\n\n();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM