Looks simple. When you detect a motive like a number inside curly brackets it should be replaced by the square of the number. If no replacement where done you are finished. If some replacement where done you do it again (because what was just replaced may be now inside curly brackets) and so on.
The first part (replacement) can be done using regex, the second part can be done either recursively either or iteratively.
Below some code snippet that should help you understand the details (not the full answer, but not far). The goal of the exercice seems to be to help you understand preg_replace()
parameters.
<?php
$count = 0;
echo preg_replace('/[{](\d+)[}]/e', '$1*$1', '{{{2}}}', -1, $count);
echo "\n";
echo "$count replacement done\n";
?>
As others proposed full solutions, here his mine:
<?php
function square($str){
$count = 0;
do {
$str = preg_replace('/[{](\d+)[}]/e', '$1*$1', $str, -1, $count);
} while ($count);
return $str;
}
echo square('{3}')."\n"; // have this return 9
echo square('{6}')."\n"; // have this return 36
echo square('{{{2}}}')."\n"; // have this return 256
echo square('{9}{12}')."\n"; // have this return 81144
echo square('{{5}}')."\n"; // have this return 125
echo square('adscdc{4}{{3}}')."\n"; // have this return adscdc1681
?>
If your are preoccupied with compatibility issues (because hardened php installation may forbid use of /e) just use preg_replace_callback
instead of preg_replace
like below (use anonymous function available as of PHP 5.2.3, for older php version, you can use create_function()
).
function square($str){
$count = 0;
do {
$str = preg_replace_callback('/[{](\d+)[}]/',
function($m) {return $m[1]*$m[1];},
$str, -1, $count);
} while ($count);
return $str;
}
For curious readers, as someone else suggested a python version, below is a possible perl equivalent:
#!/usr/bin/perl
my @tests = ('{3}','{6}','{{{2}}}','{9}{12}','{{5}}', 'adscdc{4}{{3}}');
sub square {
my $str = pop;
while ($str =~ s/[{](\d+)[}]/$1*$1/e) {};
return $str;
}
for my $str (@tests){
print "$str --> ".square($str)."\n" ;
}
There security mechanisms in Perl to avoid injections because of evil user inputs different than blindly rejecting all evals. For those interested you can have a look here.
And two other shorter python versions, recursive:
import re
test = ['5','{3}','{6}','{{{2}}}','{9}{12}','adscdc{4}{{3}}']
def square(txt):
txt2 = re.sub('{(\d+)}',lambda m: str(int(m.group(1)) ** 2) , txt)
if txt2 == txt:
return txt
return square(txt2)
for x in test:
print("%s --> %s" % (x, square(x)))
and non recursive
import re
test = ['5','{3}','{6}','{{{2}}}','{9}{12}','adscdc{4}{{3}}']
def square(txt):
oldtxt = None
while oldtxt != txt:
oldtxt = txt
txt = re.sub('{(\d+)}',lambda m: str(int(m.group(1)) ** 2) , oldtxt)
return txt
for x in test:
print("%s --> %s" % (x, square(x)))