Php替换和concat

时间:2012-05-28 10:23:16

标签: php replace concat

我需要在随机字符串中替换和连接一些值,我将值存储在数组中。

$search = array('dog', 'tree', 'forest', 'grass');
$randomString = "A dog in a forest";

如果一个或多个数组值与随机字符串匹配,那么我需要像这样的替换:

$replacedString = "A @dog in a @forest";

有人可以帮助我吗?

THX。

4 个答案:

答案 0 :(得分:8)

foreach (explode(' ', $randomString) as $word) {
  $replacedString .= in_array($word, $search) ? "@$word " : "$word ";
}

echo $replacedString;  // A @dog in a @forest

答案 1 :(得分:1)

foreach($search as $word)
{
  $randomString = str_replace($word,"@".$word,$randomString);
}

答案 2 :(得分:1)

不确定我是否理解您正在尝试正确执行的操作,但请查看str_replace()功能

并尝试类似

的内容
foreach($search as $string)
{
    $replacement[] = "@".$search;
}

$new_string = str_replace($search, $replacement, $randomString);

答案 3 :(得分:0)

这应该适合你:

$words = explode(" ", $randomString);

foreach($words as $word){
   if(in_array($word, $search)){
      $word = "@$word";
   }
}

$replacedString = implode(" ", $words);