10

I am trying to find and replace binary values in strings:

$str = '('.chr(0x00).chr(0x91).')' ;
$str = preg_replace("/\x00\x09/",'-',$str) ;

But I am getting "Warning: preg_replace(): Null byte in regex" error message.

How to work on binary values in Regex/PHP?

Digerkam
  • 1,826
  • 4
  • 24
  • 39

1 Answers1

16

It is because you are using double quotes " around your regex pattern, which make the php engine parse the chars \x00 and \x09.

If you use single quotes instead, it will work:

$str = '(' . chr(0x00) . chr(0x91) . ')' ;
$str = preg_replace('/\x00\x09/', '-', $str) ;

But your regex seems also not to be correct, if I understood your question correctly. If you want to replace the chars \x00 and \x91 with a dash -, you must put them into brackets []:

$str = preg_replace('/[\x00\x91]/', '-', $str) ;
RickWeb
  • 1,765
  • 2
  • 25
  • 40
Елин Й.
  • 953
  • 10
  • 25
  • 1
    Came across this error while allowing dynamic regex "match" strings. Wasn't sure of a fix until I came across this answer. Combining the above into this worked great for me! `$matchString = str_replace(chr(0), '\x00', $matchString);` – AlbinoDrought Jul 24 '17 at 17:03
  • Worked fro me. Thank you! – geeves Mar 23 '18 at 21:38