preg_match_all with callback?
Asked Answered
T

2

8

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});
Topazolite answered 5/1, 2015 at 23:23 Comment(0)
M
8

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.

Microcyte answered 5/1, 2015 at 23:26 Comment(0)
D
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);
});
Dempster answered 24/1, 2019 at 15:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.