Search code examples
phpregexpreg-replace

preg_replace reuse matched value in replacement value


I want to perform value replacement based on matched value. The replacement expression has calculation based on matched value.

regex

<?php
 $re = '/<w:d([^\[]+)\/>/m';
 $str = '<w:d2/>';
 //$subst = "<w:ind w:left='.eval(\"return \".\"720*$1;\").' w:right=\"\"/>";
 $subst = "<w:ind w:left='".eval("return 720*$1;")."' w:right=\"\"/>";
 $result = preg_replace($re, $subst, $str);
 echo "The result of the substitution is ".$result;
?>

I want to multiply 720 with matched value an return it in string.

I got error :

syntax error, unexpected '1' (T_LNUMBER), expecting variable (T_VARIABLE) or '{' or '$' : eval()'d code on line 1


Solution

  • The error shown because variable must start with letter or underscore. So,$1 could not use as variable. Using preg_replace_callback, I can call first captured value using matched array index 1. @Farray has gave detailed answer (here) related to this issues.

    $result=preg_replace_callback($re, function($matches)
      {
        return "<w:ind w:left='".(720*$matches[1])."' w:right='".(720*$matches[1])."'/>";
      }, $str);