如何将此javascript函数转换为PHP?

时间:2022-04-08 07:46:46
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.?

我的问题是。 c是经过str时发现的角色吗?如果是这样,你怎么能在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)

我在PHP中有这个但我意识到现在它是错的(因为它使用字符串而不是找到的字符)

1 个解决方案

#1


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.

e修饰符指定应执行第二个参数中的代码。这基本上是通过使用为每次替换运行的create_function()创建一个新函数来完成的。您还必须添加paranthesis来捕获模式。

Using it like this:

像这样使用它:

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

Yields:

foo!10!!9!!92!bar baz !13!quux

#1


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.

e修饰符指定应执行第二个参数中的代码。这基本上是通过使用为每次替换运行的create_function()创建一个新函数来完成的。您还必须添加paranthesis来捕获模式。

Using it like this:

像这样使用它:

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

Yields:

foo!10!!9!!92!bar baz !13!quux