$string = ":abc and :def have apples.";
$replacements = array('Mary', 'Jane');
Run Code Online (Sandbox Code Playgroud)
应成为:
Mary and Jane have apples.
Run Code Online (Sandbox Code Playgroud)
现在我这样做:
preg_match_all('/:(\w+)/', $string, $matches);
foreach($matches[0] as $index => $match)
$string = str_replace($match, $replacements[$index], $string);
Run Code Online (Sandbox Code Playgroud)
我可以在一次运行中使用preg_replace之类的东西吗?
可能重复:
用php替换多个占位符?
我有一个.txt文件作为模板工作.我已经制作了几个占位符{{NAME}},我想用变量替换它们.最有效的方法是什么?请记住,我的模板中有大约10个占位符.
有没有比str_replace更好的方法?
说我有这个HTML:
<html>
<head>
<title>Hello [[USER_FIRST_NAME]]</title>
</head>
<body>
<p>Hi, [[USER_FIRST_NAME]] [[USER_LAST_NAME]]!</p>
<p><a href="mailto:[[USER_EMAIL]]">[[USER_EMAIL]]</a></p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我需要preg_replace所有[[FOOBAR]]带有价值观的代币.
最终结果:
<html>
<head>
<title>Hello John</title>
</head>
<body>
<p>Hi, John Smith!</p>
<p><a href="mailto:john@smith.com">john@smith.com</a></p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)