0

In my text editor (phpStorm, notepad++, jedit, ect.) I have strings like:

....    $this->request_json['store-user-id'] .....
....    $this->request_json['deviceID'] ....

I need to replace them to:

$this->request->store_user_id
$this->request->device_id

i.e.

search: \-\>request_json\[\"([\w_\-]+)\"\]
replace: ->request->$1

BUT: I need additional inline substitution "-" -> "_", transformation to lower case and preceding every capital letter with "_".

Is that possible using perl-style regex? Maybe recursive?

Tertium
  • 6,049
  • 3
  • 30
  • 51
  • In Notepad++ 6.0 or higher, you can use "PCRE (Perl Compatible Regular Expression) Search/Replace" (source: http://sourceforge.net/apps/mediawiki/notepad-plus/?title=Regular_Expressions). So you can use a regex like `(. )([A-z])(.+)` with a replacement argument like `\1\U\2\3` – Stephan Jan 15 '15 at 09:34
  • Thank you. Where I can find info about these interesting replace arguments? there is nothing in notepad++ help – Tertium Jan 15 '15 at 10:08
  • 1
    Check this link instead: http://letconex.blogspot.fr/2013/06/how-to-use-regular-expressions-in.html. See `9. Substitutions` – Stephan Jan 16 '15 at 08:13

2 Answers2

0

just apply this 4 successive regex substitutions on your $txt strings

$txt =~ s/_json\[\'/->/;
$txt =~ s/']//;
$txt =~ s/([a-z])([A-Z])/\1_\2/g;
$txt =~ tr/[A-Z]/[a-z]/;
jjpcondor
  • 1,386
  • 1
  • 19
  • 30
  • I work with big php document, so substitution must be made only in found subpatterns. I search the way to "postprocess" regexp result. the only way I see now is extracting all found strings by preg_match_all and then work with them using preg_replace, str_replace and strtolower. – Tertium Jan 15 '15 at 09:38
0

Finally solved the problem in php:

$fstr = implode("", file("file_with_text_to_replace.php"));
$rfstr = preg_replace_callback("/\\-\\>request_json\\[(?:\\\"|\\')([\\w_\\-]+)(?:\\\"|\\')\\]/",
             function ($matches)
             {
               //any post-processing
               return  "->request->" . str_replace("-","_", $matches[1]);
             },
             $fstr);

It's the most powerful solution. I'm a little lost touch with php these days, but I'm very surprised that nobody pointed to this php function. It gives full control over the search result, impossible in text editors. Brilliant!

Tertium
  • 6,049
  • 3
  • 30
  • 51
  • 1
    You're escaping too much characters, `-`, `>`, `'` don't need to be escaped, `\w` already includes `-` and single backslashes are enough to escape `"`, `[` and `]`. You regex'll become much more readable. – Toto Jan 15 '15 at 11:09