preg_replace在替换值中重复使用匹配的值

huangapple go评论106阅读模式
英文:

preg_replace reuse matched value in replacement value

问题

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

[regex][1]

    <?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 "替换的结果是:".$result;
    ?>

我想将匹配到的值乘以720并将其返回为字符串。

我遇到了错误:

> 语法错误,意外的 '1' (T_LNUMBER),期望变量 (T_VARIABLE) 或 '{' 或 '$':在第1行 eval() 的代码
[1]: https://regex101.com/r/8PIsky/1
英文:

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

答案1

得分: 0

以下是您要翻译的内容:

"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);
英文:

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

huangapple
  • 本文由 发表于 2023年3月7日 14:51:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75658778.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定