views:

132

answers:

1
function escCtrlChars(str) 
{ 
    return str.replace(/[\0\t\n\v\f\r\xa0'"!-]/g, 
             function(c) { 
                 return '!' + c.charCodeAt(0) + '!'; 
    });
}

Ok this is a function that replaces control characters from a string with another string starting and ending with !

My question is. Is c the character found while going through str?
If so how can you mimic this function in PHP.?

function escCtrlChars($str)
{
    return preg_replace('/[\0\t\n\v\f\r\'\"!-]/i', "!".ord($str[0])."!", $str);
}

I had this in PHP but i realize now it's wrong (since it uses the string and not the character found)

+4  A: 

Try:

function escCtrlChars($str)
{
    return preg_replace('/([\0\t\n\v\f\r\'\"!-])/ie', '"!".ord(substr("$1",0,1))."!"', $str);
}

The e modifier specifies that the code in the second argument should be executed. This is basically done by creating a new function using create_function() that is run for each replacement. You also have to add paranthesis to capture the pattern.

Using it like this:

$str = "foo\n\t'bar baz \rquux";
echo escCtrlChars($str)."\n";

Yields:

foo!10!!9!!92!bar baz !13!quux
Emil H
That's a neat functinality, I'm not getting the correct results though. Looking into if there is something else hindering it.
Ólafur Waage
I'll try the code and see if I can spot the error. Hold on.
Emil H
You added the parenthesis afterwards. They did the trick.
Ólafur Waage
Great. :) This syntax can probably be made cleaner in the newly released PHP 5.3 which supports real closures. Haven't tried it though.
Emil H