繁体   English   中英

如何用 PHP 中的变量值替换字符串

[英]How to replace a string with a variable value in PHP

我有以下 function ,它接受一个字符串{{#x,y}}并在xy之间选择一个随机值:

$res = preg_replace_callback('/{{[#]([\w,]{1,})}}/', function ($match)  {
          $numbers = explode(',', $match[1]);
          shuffle($numbers);
          return isset($numbers[0]) ? $numbers[0] : '{#'.$match[0].'}';
        }, $res);

我该如何修改它以使其执行以下操作:

{{$string, "val"}} - 如果$string为空或未定义,则将其设置为"val" ,否则将其设置为$string

它应该检查$string是否已经是一个存在且不为空的变量,然后将其替换为$string的真实值,否则使用val

例子:

$string = "Hello";
$res = 'This is a test {{$string, "Ok"}}';

//call function

echo $res // This is a test Hello

另一个例子:

$res = 'This is a test {{$string, "Ok"}}';

//call function

echo $res // This is a test Ok

我已经尝试了您使用此代码块提供的示例并且它有效。

<?php
$string = "Hello";
$subject  = 'This is a test {{$string, "Ok"}}';

$varsInContext = get_defined_vars();
var_dump(parseText($subject, $varsInContext)); //This is a test Hello

function parseText(string $completeString, array $varsInContext):string {
    
    $pattern = '/(?<blockTextToReplace>{{\$(?<variableToEval>.+),\s?"(?<fallbackValue>[\w\d]+)"}})/';
    preg_match($pattern,$completeString,$matches);    
    
    
    if(!empty($matches)){
        $variableToEval = $matches['variableToEval'];
        $fallbackValue = $matches['fallbackValue'];
        $finalValue = !empty($varsInContext[$variableToEval]) ? $varsInContext[$variableToEval] : $fallbackValue;
        
        $blockTextToReplace = $matches['blockTextToReplace'];
        $finalText = str_replace($blockTextToReplace, $finalValue, $completeString);
        
        return $finalText;
    }
    
    return $completeString;
}

考虑到它使用了上下文中的所有变量,如果“主题”中提供的变量将在同一个 scope 中可用,您可以使用变量变量来优化过程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM