php中的唯一关键字,用定义的变量替换

时间:2014-10-31 12:42:35

标签: php preg-replace deprecated

我想在php中使用一个函数来替换一些具有定义值的唯一单词。 即

define("URL","http://example.com");
define("WEBSITE","Stackoverflow");
$string = "This is a dummy text with {URL} & name of website {WEBSITE}";

现在我希望输出为: 这是一个带有http://example.com&的虚拟文本。网站名称Stackoverflow。

我的功能在PHP 5.4中运行良好

define("URL","http://example.com");
define("WEBSITE","Stackoverflow");
function magicKeyword($data) {
$URL = URL;
$SITENAME = WEBSITE;
return preg_replace('/\{([A-Z]+)\}/e', "$$1", $data);
}

但在php 5.5中他们弃用了/ e修饰符。

不推荐使用:preg_replace():不推荐使用/ e修饰符,而是使用preg_replace_callback

现在请帮助我。

2 个答案:

答案 0 :(得分:1)

为什么你不能简单地从函数

返回$string
define("URL","http://example.com");
define("WEBSITE","Stackoverflow");
function magicKeyword() {
  $URL = URL;
  $SITENAME = WEBSITE;
  $string = "This is a dummy text with $URL & name of website $SITENAME";
  return $string;
}
echo magicKeyword(); //This is a dummy text with http://example.com & name of website Stackoverflow 

str_replace()

define("URL","http://example.com");
define("WEBSITE","Stackoverflow");
$string = "This is a dummy text with {URL} & name of website {WEBSITE}";
function magicKeyword($string) {
$URL = URL;
$SITENAME = WEBSITE;
$string = str_replace(array('{URL}', '{WEBSITE}'), array($URL, $SITENAME), $string);
return $string;
}
echo magicKeyword($string);

答案 1 :(得分:0)

回调函数的用法如下:

define("URL","http://example.com");
define("WEBSITE","Stackoverflow");

$string = "This is a dummy text with {URL} & name of website {WEBSITE}";

function magicKeyword($data) {
    return preg_replace_callback('/\{([A-Z]+)\}/', "magicKeywordCallback", $data);
}

function magicKeywordCallback($matches) {
    if (defined($matches[1]))
        return constant($matches[1]);
    // otherwise return the found word unmodified.
    return $matches[0];
}

$result = magicKeyword($string);
var_dump($result);

结果:

  

string(76)“这是一个虚拟文本,带有http://example.com&网站名称Stackoverflow”