PHP - replace a string with a variable named like the string

那年仲夏 提交于 2020-01-19 10:06:34

问题


so the string is like this:

"bla bla bla {VARIABLE} bla bla"

when I use this string somewhere in a function I want to replace {VARIABLE} with $variable (or any other uppercase strings with wrapped within {} charcters). $variable (and any other variables) will be defined inside that function

Can i do this?


回答1:


$TEST = 'one';
$THING = 'two';
$str = "this is {TEST} a {THING} to test";

$result = preg_replace('/\{([A-Z]+)\}/e', "$$1", $str);



回答2:


Use a regular expression to find all substitutions, then iterate over the result and replace them. Be sure to only allow variables you would want to expose.

// white list of variables
$allowed_variables = array("test", "variable", "not_POST", "not_GET",); 

preg_match("#(\{([A-Z]+?)\}#", $text, $matches);

// not sure the result is in [1], do a var_dump
while($matches[1] as $variable) { 
    $variable = strtolower($variable);

    // only allow white listed variables
    if(!in_array($variable, $allowed_variables)) continue; 

    $text = str_replace("{".$match."}", $$match, $text);
}



回答3:


Building on some of the other answers (especially Bill Karwin's & bouke)...

 class CurlyVariables {

  private static $_matchable = array();
  private static $_caseInsensitive = true;

  private static function var_match($matches)
  {
    $match = $matches[1];

    if (self::$_caseInsensitive) {
      $match = strtolower($match);
    }

    if (isset(self::$_matchable[$match]) && !is_array(self::$_matchable[$match])) {
      return self::$_matchable[$match];
    }

    return '';
  }

  public static function Replace($needles, $haystack, $caseInsensitive = true) {
    if (is_array($needles)) {
      self::$_matchable = $needles;
    }

    if ($caseInsensitive) {
      self::$_caseInsensitive = true;
      self::$_matchable = array_change_key_case(self::$_matchable);
    }
    else {
      self::$_caseInsensitive = false;
    }

    $out = preg_replace_callback("/{(\w+)}/", array(__CLASS__, 'var_match'), $haystack);

    self::$_matchable = array();

    return $out;
  }
}

Example:

echo CurlyVariables::Replace(array('this' => 'joe', 'that' => 'home'), '{This} goes {that}', true);



回答4:


Using $$vars and $GLOBALS both represent security risks. The user should be able to explicitly define the list of tags that are acceptable.

Below is the simplest single-function general solution I could devise. I chose to use double-braces as tag delimiters, but you can modify it easily enough.

/**
 * replace_tags replaces tags in the source string with data from the vars map.
 * The tags are identified by being wrapped in '{{' and '}}' i.e. '{{tag}}'.
 * If a tag value is not present in the tags map, it is replaced with an empty
 * string
 * @param string $string A string containing 1 or more tags wrapped in '{{}}'
 * @param array $tags A map of key-value pairs used to replace tags
 * @param force_lower if true, converts matching tags in string via strtolower()
 *        before checking the tags map.
 * @return string The resulting string with all tags replaced.
 */
function replace_tags($string, $tags, $force_lower = false)
{
    return preg_replace_callback('/\\{\\{([^{}]+)\}\\}/',
            function($matches) use ($force_lower, $tags)
            {
                $key = $force_lower ? strtolower($matches[1]) : $matches[1];
                return array_key_exists($key, $tags) 
                    ? $tags[$key] 
                    : '';
            }
            , $string);
}

[edit] Added force_lower param

[edit] Added force_lower var to use list - Thanks to whomever started the rejected edit.




回答5:


This will work....

$FOO = 'Salt';
$BAR = 'Peppa';
$string = '{FOO} and {BAR}';
echo preg_replace( '/\{([A-Z]+)\}/e', "$$1", $string );

but it just seems like an awful idea.




回答6:


The following is another solution, but I agree with other folks who are dubious about whether this is a wise thing for you to do.

<?php

$string = "bla bla bla {VARIABLE} bla bla";
$VARIABLE = "foo";

function var_repl($matches)
{
  return $GLOBALS[$matches[1]];
}

echo preg_replace_callback("/{(\w+)}/", "var_repl", $string);



回答7:


I am glad I have found Bill Criswell's solution, but is it also possible to replace such variables:

string tmp = "{myClass.myVar}";

Where the PHP code would be something like:

class myClass
{
    public static $myVar = "some value";
}



回答8:


$data_bas = 'I am a {tag} {tag} {club} {anothertag} fan.'; // Tests

$vars = array(
  '{club}'       => 'Barcelona',
  '{tag}'        => 'sometext',
  '{anothertag}' => 'someothertext'
);

echo strtr($data_bas, $vars);


来源:https://stackoverflow.com/questions/3763773/php-replace-a-string-with-a-variable-named-like-the-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!