1
votes

How I can change the following code preg_replace (deprecated in PHP 5.6):

$ Encoded = preg_replace ('/ ([\ 000- \ 011 \ 013 \ 014 \ 016- \ 037 \ 075 \ 077 \ 137 \ 177- \ 377]) / and',                "'='. Sprintf ('% 02X', ord ('\\ 1'))", $ encoded);

with preg_replace_callback?

1
Could you please format it correctly? Please also provide an example string. - Wiktor Stribiżew
Try $encoded = preg_replace_callback('/([\000-\011\013\014\016-\037\075\077\137\177-\377])\/and/', function($m) { return '='. sprintf('%02X', ord($m[1])); }, $encoded); - Wiktor Stribiżew
Excellent Wiktor, now it all seems ok. Thanks a lot! - Alexander

1 Answers

0
votes

You may use preg_replace_callback like this:

$re = '/([\000-\011\013\014\016-\037\075\077‌​\137\177-\377])\/and‌​/';
$encoded = preg_replace_callback($re, function($m) { 
     return '='. sprintf('%02X', ord($m[1])); 
}, $encoded);

where $m is the match object containing the match and optional captures that you may acces via indices. E.g. $m[1] is the capture group #1 value (ie. of the ([\000-\011\013\014\016-\037\075\077‌​\137\177-\377]) subpattern).