preg_replace重用替换值中的匹配值

preg_replace reuse matched value in replacement value

提问人:Premlatha 提问时间:3/7/2023 更新时间:3/7/2023 访问量:53

问:

我想根据匹配的值执行值替换。替换表达式具有基于匹配值的计算。

正则表达式

<?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;
?>

我想将 720 与匹配值相乘,并以字符串形式返回它。

我收到错误:

语法错误,意外的“1”(T_LNUMBER),期望变量 (T_VARIABLE) 或“{”或“$”:第 1 行的 eval()'d 代码

php 正则表达式 preg-replace

评论

0赞 CBroe 3/7/2023
摆脱邪恶的评估,并使用 php.net/manual/en/function.preg-replace-callback.php
0赞 Premlatha 3/7/2023
是的,你是对的。能够使用preg_replace_callback解决它。谢谢。

答:

0赞 Premlatha 3/7/2023 #1

显示的错误,因为变量必须以字母或下划线开头。因此,$1 不能用作变量。使用 preg_replace_callback,我可以使用匹配的数组索引 1 调用第一个捕获的值。@Farray已经给出了与此问题相关的详细答案(此处)。

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