0

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

IE

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

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

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

有人能帮我吗?

谢谢。

4

4 回答 4

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

echo $replacedString;  // A @dog in a @forest
于 2012-05-28T10:28:45.367 回答
1
foreach($search as $word)
{
  $randomString = str_replace($word,"@".$word,$randomString);
}
于 2012-05-28T10:30:41.390 回答
1

不确定我是否理解您要正确执行的操作,但请查看str_replace()函数

并尝试类似的东西

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

$new_string = str_replace($search, $replacement, $randomString);
于 2012-05-28T10:33:45.343 回答
0

这应该适合你:

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

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

$replacedString = implode(" ", $words);
于 2012-05-28T10:29:35.643 回答