Jesse Schokker
Jesse Schokker

Reputation: 896

Replace in string with specific word exceptions

I wish to remove the classes from class properties in my PHP project. The string I want to find and replace look like this: private Selector $Selector; Keep in mind that the class (in this case "Selector") is variable.

I've already tried coming up with a solution myself, however, this pattern also matches private function sendEventRelayMessage( Tracker $

find private (.*?) \$\b

replace private \$

Upvotes: 0

Views: 104

Answers (1)

Nicolas
Nicolas

Reputation: 8670

You need a more specific Regex. If we follow PHP's rules on class name, it gives us a pretty good regex already to check class name. All you need is to remove reserved word and you got yourself a solution.

I've come up with this regex that does what you are looking for

private ((?!function)[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]+) .+

The regex will look for the keyword private, followed by a space and any characters that are valid class name caracter. It will filter out the keyword function (negative lookahead) then matches a spaces and anything after that.

Here is a more complete explaination on how the regex works.

Regular expression visualization

Upvotes: 1

Related Questions