谁能解释一下这个正则表达式的用法?
我想 chop 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,并且不想从字符串中 chop 它们(如果有的话)。 Ascii 32 以下的其他字符应被 chop 。
最佳答案
好吧,鉴于:
- 0x09 = 标签
- 0x12 = 换行
- 0x15 = 回车
然后除 上面的任何内容(仍然是 <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
])被保留,我会说这就是你的意思之后。
关于php - JavaScript 和 PHP 正则表达式的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18512305/