不知道如果PHP可以做到这一点,所以我认为我会问专家:传递变量转换成字符串
我想有一个字符串数组中,我有一个占位符:
array (
1 => "this is string $1",
2 => "this is string $2");
然后,我想在很多页面中引用此值,并传递相关页面的值:
例如 print(array ['1'],“value to replace $ 1”)
这可能吗?
感谢
不知道如果PHP可以做到这一点,所以我认为我会问专家:传递变量转换成字符串
我想有一个字符串数组中,我有一个占位符:
array (
1 => "this is string $1",
2 => "this is string $2");
然后,我想在很多页面中引用此值,并传递相关页面的值:
例如 print(array ['1'],“value to replace $ 1”)
这可能吗?
感谢
我建议使用sprintf()
echo sprintf('this string is %s', $array[1]);
这不适用于字符串本地化的情况。 - 令牌的顺序可能不同。 – Erbureth
如果你做得对,这也适用于本地化的字符串:'sprintf(translate('this string is%s'),translate($ array [1]));'和'这个字符串是%s'被翻译到'Der Text lautet%s'(和'$ array [1]'到“I-dont-care”;))。一切都很好。使用编号占位符,您甚至可以更改命令'%2 $ s是第二个参数,%1 $ s是第一个' – KingCrunch
不,它不是 - “这是$ 2的$ 1” - >“Sore wa $ 2 no $ 1 “编辑:对,没有那个。 – Erbureth
我建议正则表达式替换文本标记。 http://www.php.net/manual/en/function.preg-replace.php
实施例:
$template = "Invoice was issued on <<ISSUED-DATE>> and has to be paid on <<DUE-DATE>> at the latest";
$patterns = array(
"/".preg_quote("<<ISSUED-DATE>>")."/",
"/".preg_quote("<<DUE-DATE>>")."/"
);
$replacements = array(
$issued,
$due
);
$newtext = preg_replace($patterns, $replacements, $template);
正则表达式对于简单字符串替换只是过大。 – KingCrunch
我同意 - 但有点过大,然后让我以任何顺序放置多个字符串。我喜欢这个理论,但会与sprintf()一起开始。这为赛道的灵活性提供了更多的灵活性 –
是否占位符必须为每个阵列值不同?即,你的例子中的两个字符串是不是使用“$ 1”作为占位符的原因是什么? – Farray