Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append array index using search/replace?

Tags:

regex

Need to convert every occurrence of the string "gotcha" in a text file to gotcha[1], gotcha[2], gotcha[3] etc. (in order).

I can do this easily with a simple C++ program but wondered if there's an easier way. Regex-replace in my text editor doesn't appear to be capable. After some surfing, it looks like Perl, sed, or awk might be the right tool, but I'm not familiar with any of those.

like image 204
mathematrucker Avatar asked Apr 29 '26 04:04

mathematrucker


1 Answers

I don't know if other languages support this, but in PHP you have the e modifier, which is ofcourse bad to use and is deprecated in recent PHP versions. So this is a POC in PHP:

$string = 'gotcha wut gotcha wut gotcha wut gotcha PHP gotcha rocks gotcha !!!'; // a string o_o
$i = 0; // declaring a variable i which is 0

echo preg_replace('/gotcha/e', '"$0[".$i++."]"', $string);


/*
   + echo --> output the data
         + preg_replace() --> function to replace with a regex
                + /gotcha/e
                    ^     ^--- The e modifier (eval)
                    --- match "gotcha"

                + "$0[".$i++."]"
                  $0 => is the capturing group 0 which is "gotcha" in this case"
                  $i++ => increment i by one
                  Ofcourse, since this is PHP we have to enclose string
                 between quotes (like any language :p)
                 and concatenate with a point:  "$0["   .   $i++   .   "]"

                + $string should I explain ?
*/

Online demo.


And ofcourse, since I know there are some haters on SO I'll show you the right way to do this in PHP without the e modifier, let's preg_replace_callback !

$string = 'gotcha wut gotcha wut gotcha wut gotcha PHP gotcha rocks gotcha !!!';
$i = 0;
// This requires PHP 5.3+
echo preg_replace_callback('/gotcha/', function($m) use(&$i){
    return $m[0].'['.$i++.']';
}, $string);

Online demo.

like image 176
HamZa Avatar answered May 02 '26 05:05

HamZa