7

I'm interested in replace numeric matches in real time and manipulate them to hexadecimal.

I was wonder if it's possible without using foreach loop.

so iow...

every thing in between :

= {numeric value} ;

will be manupulated to :

= {hexadecimal numeric value} ;

preg_match_all('/\=[0-9]\;/',$src,$matches);

Is there any callback to preg_match_all so instead of preform a loop afterwards I can manipulate them as soon as preg_match_all catch every match (real time).

this is not correct syntax but just so you can get the idea :

preg_match_all_callback('/\=[0-9]\;/',$src,$matches,{convertAll[0-9]ToHexadecimal});
alex
  • 479,566
  • 201
  • 878
  • 984
iprophesy
  • 175
  • 3
  • 9

2 Answers2

6

You want preg_replace_callback().

You would match them with a regex like /=\d+?;/ and then your callback would look like...

function($matches) { return dechex($matches[1]); }

Combined, it gives us...

preg_replace_callback('/=(\d+?);/', function($matches) { 
   return dechex($matches[1]);
}, $str);

CodePad.

Alternatively, you could use positive lookbehind/forward to match the delimiters and then pass 'dechex' straight as the callback.

alex
  • 479,566
  • 201
  • 878
  • 984
1

Or you could use T-Regx tool, which is far better! (automatic delimiters, exceptions instead of warnings, cleaner API)

pattern('=(\d+?);')->replace($str)->group(1)->callback('dechex');

or if you prefer the anonymous function

pattern('=(\d+?);')->replace($str)->group(1)->callback(function (Group $group) {
    return dechex($group);
});
Danon
  • 2,771
  • 27
  • 37