preg replace callback - How to create a pattern to use in preg_replace_callback() function in PHP
I am upgrading my PHP Application from PHP 5 to PHP 7 for which I am required to replace all the references of preg_replace() function to preg_replace_callback() function.
I am having a hard time creating the $pattern parameter for preg_replace_callback() function.
Below are the code details -
The string that I am trying to match -
$bandHdrs = "{format(26,num,4)}";
Existing PHP 5 code:
$bandHFmtString = "#({)(format)([(]*)([0-9]*)([a-zA-Z0-9,']*)([)]*)(})#e";
$subBandHead = preg_replace_callback($bandHFmtString, '$this->formatSqlNumber($queryData[$r][' . "$4" . '],\'' . "$5" . '\',\'' . "$2" . '\')', $bandHdrs);
New PHP 7 code:
$bandHFmtString = "#\{format\(\[0-9]*\,\[a-zA-Z0-9]*\,\[0-9]*\)\}#";
$subBandHead = preg_replace_callback($bandHFmtString, function ($matches) use ($value) {
$firstCommaPos = strpos($matches[0],",");
$closeParenPos = strpos($matches[0],")",$firstCommaPos + 1);
$formatStr = substr($matches[0],$firstCommaPos,$closeParenPos - $firstCommaPos);
return Report::formatSqlNumber($value,$formatStr,"format");
, $bandHdrs[$key]);
Can someone help me create the $bandHFmtString pattern to match the $bandHdrs string?
Any help would be truly appreciated.
Answer
Solution:
I found the solution, the values from the matching are stored in the $matches array. Below code worked in PHP 7 -
$subBandHead = preg_replace_callback($bandHFmtString, function ($matches) use ($r,$queryData) {
$two = $matches[2];
$four = $matches[4];
$five = $matches[5];
$repl = $queryData[$r][$four];
return Report::formatSqlNumber($repl,$five,$two);
}, $bandHdrs[$key]);
Source