sjeguedes
sjeguedes

Reputation: 43

Regex: replace some pieces of php code in sublime text

I'm quite a beginner in regex and i'd like to replace some pieces of code in Sublime Text 3 editor using search and replace with regex. Here is an example i'm trying to replace:

Piece of php code to find:

self::$_config::$_params['myKey1']['myKey2']['myKey3']['myKeyn'] 

and replace it with:

self::$_config::getParam('myKey1.myKey2.myKey3.myKeyn')

One or more keys can be defined in array.

My "search" regex is:

self::\$_config::\$_params\['([a-zA-Z0-9]+)(?:(('\]\[')([a-zA-Z0-9]+))*)'\]

I'm looking for a "replace" solution to retrieve all the keys to format the code as expected (getParam() method instead of $_params property) with repeated capturing group $2: i'm not sure it is possible like this or the most adapted way to succeed. Obviously, i have a warning for $2: "A repeated capturing group will only capture the last iteration".

$2 is optional (unique key).

Each match in $3 ('\]\[') has to be replaced with a dot.

Thank you all for your answers.

Upvotes: 3

Views: 285

Answers (1)

revo
revo

Reputation: 48751

These kind of processes can't be done in one single step. All you have to do is going through at least two find / replace functions.

  • Look for all consecutive '\]\[' occurrences after a self::$_config::$_params and replace it with a .

  • Then look for \[' and \'], after $_params and end of statement respectively to replace them with getParam(' and ')

But there would be another workaround to do this...

One-liner RegEx Solution

  1. Put following string at the very end of file:

    getParam('.')
    

You can do top step manually or through a find \z and replace with getParam('.') method through all files you need (this then wouldn't make it one-liner!)

  1. Do an ALT+R to enable Regular Expression search while being on Find / Replace pane.

  2. Copy / Paste below regex into search field:

    ((self::\$_config::)\$_params\['(?=[\s\S]*(getParam\('))|\G(?!\A))(\w+)(?|'\](?!\s*\[)(?=[\s\S]*('\)))|'\]\['(?=[^.]*+(\.)))
    
  3. Copy / paste below replacement string into replacement field:

    \2\3\4\5
    
  4. Click Replace All.

  5. Remove getParam('.') from end of file.

Live demo

Upvotes: 1

Related Questions