Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_match_all with callback?

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});
like image 341
iprophesy Avatar asked Jan 05 '15 23:01

iprophesy


1 Answers

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.

like image 170
alex Avatar answered Sep 22 '22 10:09

alex