所以我一直在玩正则表达式,我的朋友挑战我写一个脚本替换字符串中的所有十六进制.他给了我一个混合了不同字符的大文件,当然还有一些十六进制字符串.
每次出现的十六进制都以前面开头\x,例如:\x55.
我认为这很简单,所以我在一些在线正则表达式测试器上尝试了这种模式: /\\x([a-fA-F0-9]{2})/
它工作得很好.
但是,当我把它扔进一些PHP代码时,它根本无法替换它.
任何人都可以给我一个正确的方向,我错了吗?
这是我的代码:
$toDecode = file_get_contents('hex.txt');
$pattern = "/\\x(\w{2})/";
$replacement = 'OK!';
$decoded = preg_replace($pattern, $replacement, $toDecode);
$fh = fopen('haha.txt', 'w');
fwrite($fh, $decoded);
fclose($fh);
Run Code Online (Sandbox Code Playgroud)
<?php
// grab the encoded file
$toDecode = file_get_contents('hex.txt');
// create a method to convert \x?? to it's character facsimile
function escapedHexToHex($escaped)
{
// return 'OK!'; // what you're doing now
return chr(hexdec($escaped[1]));
}
// use preg_replace_callback and hand-off the hex code for re-translation
$decoded = preg_replace_callback('/\\\\x([a-f0-9]{2})/i','escapedHexToHex', $toDecode);
// save result(s) back to a file
file_put_contents('haha.txt', $decoded);
Run Code Online (Sandbox Code Playgroud)
供参考,preg_replace_callback.另外,请不要使用,\w因为它实际上已翻译成[a-zA-Z0-9_].十六进制是base-16,所以你想要[a-fA-F0-9](并且i标志使它不区分大小写).
工作示例,减去文件部分.