如何将str_replace()与多个参数一起使用?

时间:2011-08-10 19:36:52

标签: php

基本上,我想同时将$city_name$ref_name与str_replace()一起使用,这样如果用户输入其中一个(或两个),则两个都被替换为实际变量形式。

为了更好地说明,这是我目前的代码;

$headlines = array('primary_headline' => $_POST['primary_headline'], 'secondary_headline' => $_POST['secondary_headline'], 'primary_subline' => $_POST['primary_subline'], 'secondary_subtext' => $_POST['secondary_subtext']);
$city_name = "Dallas";
$ref_name = "Facebook";
if(isset($headlines)) {
  foreach($headlines as $headline) {
      echo(str_replace('$city_name', $city_name, $headline));
  }
}

我基本上希望str_replace('$city_name', $city_name, $headline)成为str_replace('$city_name' AND/OR '$ref_name', $city_name AND/OR $ref_name, $headline)

任何答案或评论都将不胜感激!

1 个答案:

答案 0 :(得分:5)

http://php.net/manual/en/function.str-replace.php

$searches = array('$city_name', '$ref_name');
$replacements = array($city_name, $ref_name);
echo str_replace($searches, $replacements, $headline);