tags:

views:

74

answers:

2
$str =
preg_replace('#([\x00-\x1F])#e', '"\x" . sprintf("%02x", ord("\1"))', $str);
+1  A: 

Update:

I looked at it closer and it looks like it's converting all ascii chars in the 1-31 range to their hex equivalent with a \x prefix.

My original gut reaction guess which I've decided is incorrect:

Looks like it's urlencoding. I would probably use the built in php urlencode function instead.

Asaph
from 0 to 31, not 1.
Adriano Varoli Piazza
thanks.
lovespring
+2  A: 

It replaces every occurrence of a character with ordinal value between 0 and 31 (mostly control characters and spacing, except the actual space character) with its numeric value. The e at the end of the regex means 'evaluate the pattern as if it was PHP code', and allows for the string concatenation and the use of sprintf inside preg_replace. The regex is delimited by # instead of the more common /, for no reason in this case (it's usually done if the regex string contains /, to avoid escaping them).

For example:

<?php
$str = "\t 22 \n ducks";
$str = preg_replace('#([\x00-\x1F])#e', '"\x" . sprintf("%02x", ord("\1"))', $str);
echo $str;
?>

Outputs:

\x09 22 \x0a ducks

Take out the e from the pattern, and you get this:

"\x" . sprintf("%02x", ord(" ")) 22 "\x" . sprintf("%02x", ord(" ")) ducks

at least here.

Adriano Varoli Piazza