Web Hosting Talk







View Full Version : Need help translating 2 lines of Perl code to PHP


azizny
10-01-2008, 10:58 PM
It has been a while since I worked with Perl and can't really grasp it. I know how to convert the second line, but I put it there to make it easier to understand.


my @chars = map {chr $_} (0x20 ... 0x7e);
$text = $chars[int(rand(@chars))];
$text =~ s/[<>!&]/./g;


Any help or pointers appreciated.

Thanks,

luki
10-02-2008, 01:50 AM
This line here should do the same... double check it though.

$text = strtr(chr((int)rand(0x20,0x7e)), '<>!&', '....');

azizny
10-02-2008, 07:32 AM
Thanks..

I tried:

echo rand(0x20,0x7e);

but its printing numbers, are those the decimal values for numbers?

Thanks,

foobic
10-02-2008, 09:11 AM
A more direct translation would be something like this:
$chars = array_map("chr", range(0x20, 0x7e)); // create the array of all characters in range
$text = $chars[intval(rand(0, count($chars)))]; // pick one character at random
$text = preg_replace('/[<>!&]/', '.', $text); // replace unwanted characters with a period

It doesn't really make sense to do it this way for a single random character though - does the original code build a multiple-character random string in $text?

azizny
10-02-2008, 09:41 AM
A more direct translation would be something like this:
$chars = array_map("chr", range(0x20, 0x7e)); // create the array of all characters in range
$text = $chars[intval(rand(0, count($chars)))]; // pick one character at random
$text = preg_replace('/[<>!&]/', '.', $text); // replace unwanted characters with a period

It doesn't really make sense to do it this way for a single random character though - does the original code build a multiple-character random string in $text?

Yes it is. It was used to estimate user speed by downloading a lengthy amount of text using javascript.

Thanks alot,

Peace,