![](/img/trans.png)
[英]How can I replace a block of code in a php file using preg_replace and regex expression?
[英]How can I replace all hex using RegEx in PHP?
所以我一直在玩正則表達式,我的朋友挑戰我寫一個腳本替換字符串中的所有十六進制。 他給了我一個混合了不同字符的大文件,當然還有一些十六進制字符串。
每次出現的十六進制都以\\x
\\x55
,例如: \\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);
<?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);
供參考, preg_replace_callback 。 另外,不要使用\\w
因為它實際上已翻譯為[a-zA-Z0-9_]
。 十六進制是base-16,所以你想要[a-fA-F0-9]
(並且i
標志使它不區分大小寫)。
工作示例 ,減去文件部分。
您的問題是您沒有在PHP字符串中轉義反斜杠。 它需要是:
$pattern = "/\\\\x(\\w{2})/";
...要么:
$pattern = '/\\\\x(\\w{2})/';
......用單引號。
-
但是\\w
將匹配任何perl單詞字符,這不僅僅是十六進制字符。 我會改用字符類[a-fA-F0-9]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.