I need to refactor some PHP annotations, I want to replace string[]
with array<int, string>
.
I've tried to match the appropriate annotations with this PCRE regex:
(?<!\$|>)\w+\[\]
But it doesn't work, here's how the regex is matching:
The two latest lines shouldn't match. Is there any way to create a working regex for this or should I use create a custom script to do this?
You may use
\b(?<!\$|->)\w+\[]
See the PCRE regex demo.
Details
\b
- word boundary(?<!\$|->)
- a negative lookbehind that fails the match if there is a $
or ->
immediately to the left of the current location\w+
- 1+ word chars.\[]
- a []
substring.See PHP demo:
$str = '/** @var string[] */
/** @return string[] */
* @param Company[]|null $companies
$icons[] = static::getIconDetailsFromLink($link);
$this->properties[] = $property;';
if (preg_match_all('/\b(?<!\$|->)\w+\[]/', $str, $matches)) {
print_r($matches);
}