英文:
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.
<?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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论