How can I replace all hex using RegEx in PHP?

So, I did regular expressions, and my friend challenged me to write a script that replaced all the hex strings. He gave me a large file mixed with various characters, and, of course, several hexadecimal strings.

Each entry is preceded by hex \x, so, for example: \x55.

I thought it would be pretty easy, so I tried this pattern on some online regular expression testers: /\\x([a-fA-F0-9]{2})/

It worked great.

However, when I throw it into some kind of PHP code, it does not replace it at all.

Can someone give me a push in the right direction, where am I going wrong?

Here is 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);
+3
source share
2 answers

, PHP. :

$pattern = "/\\\\x(\\w{2})/";

... :

$pattern = '/\\x(\w{2})/';

... . - escape-

\w perl, . [a-fA-F0-9].

+2
<?php
  // grab the encoded file
  $toDecode = file_get_contents('hex.txt');

  // create a method to convert \x?? to it 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_]. Hex - base-16, [a-fA-F0-9] ( i ).

, .

+5

All Articles