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.