如何用PHP替换字符串中的变量?
-
06-07-2019 - |
题
所以我有一些看起来像这样的PHP代码:
$message = 'Here is the result: %s';
我只是用%s作为例子。它基本上是一个占位符,无论将去哪里。然后我将字符串传递给函数,我希望该函数用值替换%s。
我需要做些什么才能实现这一目标?我需要做一些正则表达式,并使用preg_replace(),或什么?或者有更简单的方法吗?
解决方案
您实际上可以使用 sprintf 函数,该函数将返回格式化字符串并将您的变量放在占位符。
它还为您提供了如何格式化和显示字符串的强大功能。
$output = sprintf("Here is the result: %s for this date %s", $result, $date);
其他提示
如果您使用%s
,我认为这与printf用于字符串的占位符相同。所以你可以这样做:
$text = sprintf($message, "replacement text");
认为至少应该起作用......
$find = array(
'#name#',
'#date#'
);
$search = array(
'someone\'s name',
date("m-d-Y")
);
$text_result = str_replace($find, $search, $text);
我通常在我的代码中使用它,从中获取$ text 一些text / html文件然后将$ text_result作为输出
您可以使用 sprintf
,其工作方式与C相似 printf
和 sprintf
函数。
尝试动态变量:
$placeholder = 's';
str_replace("%".$placeholder,$placeholder,$message);
然后%s将被$ s替换为变量
不隶属于 StackOverflow