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)

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

That's a neat functinality, I'm not getting the correct results though. Looking into if there is something else hindering it.
Great. :) This syntax can probably be made cleaner in the newly released PHP 5.3 which supports real closures. Haven't tried it though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.