谁能解释这个正则表达式的用法?
我想截断ASCII码少于32的字符,除了
水平制表符,换行和回车。
下面的代码会相应地工作吗?还是需要更改?
JavaScript代码:
var text = text.replace(/[\x00-\x09\x0A\x0D-\x2F]+/, "");
PHP代码
$val = preg_replace('/[\x00-\x09\x0A\x0D-\x2F]/', '',$val);
编辑
我想保留LF,HT和CR,并且不想从String截断它们(如果有的话)。Ascii 32以下的其他字符应被截断。
好吧,鉴于:
那么什么,但上述(仍然<32
)看起来是这样的:
/[\x00-\x08\x10\x11\x13\x14\x16-\x1F]/
而且我认为您的意思是排他匹配(最多但不包括32个),否则最后一个十六进制代码应为\x20
。
$orig = "This is a sample document. It contains:\r\n"
. "\t* horizontal tabs,\r\n"
. "\t* line feeds, and\r\n"
. "\t* carriage returns\r\n"
. "\r\n"
. "These characters are not to be removed. However, other characters, such as:\r\n"
. "\r\n"
. "\t'\x06' (ACK),\r\n"
. "\t'\x07' (BEL),\r\n"
. "\t'\x1B' (ESC)\r\n"
. "\t(others)\r\n"
. "\r\n"
. "And other characters < ordinal 32 should be removed.";
$modif = preg_replace('/[\x00-\x08\x10\x11\x13\x14\x16-\x1F]/', '', $orig);
echo str_repeat('=', 50) . PHP_EOL;
echo (strlen($orig) == strlen($modif) ? "Failed" : "Success") . PHP_EOL;
echo str_repeat('=', 50) . PHP_EOL;
echo PHP_EOL;
echo $modif;
基于该$modif
比短$orig
(3个字[ \x06
,\x07
,\x1B
]),但空白字符([ \x09
,\x12
,\x15
])被保存下来,我会说这是你追求的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句