So I've been toying around with Regular Expressions, and my friend challenged me to write a script that replaced all hex within a string. He gave me a large file mixed with different characters and, of course, some hex strings.
Each occurrence of hex is preceded with \x, so for example: \x55.
I thought it'd be pretty easy, so I tried out this pattern on some online regex tester: /\\x([a-fA-F0-9]{2})/
It worked perfectly.
However, when I throw it into some PHP code, it fails to replace it at all.
Can anyone give me a nudge into the right direction of where I'm going wrong?
Here's my code:
$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);
hex.txt?0-9andA-F, while your regular expression will match characters other than these.\wis any letter or number, but hex is only 0-9 and A-F. You could replace it with [0-9a-fA-F]