madimper
madimper

Reputation: 67

Php replace and concat

I need to replace and concat some values in a random string, i store the values in an array.

I.e.

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

If one or more array values matches the random string then i need a replace like this:

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

Can someone help me?

Thx.

Upvotes: 0

Views: 1405

Answers (4)

Kasia Gogolek
Kasia Gogolek

Reputation: 3414

Not sure if I understand what you're trying to do correctly but have a look at str_replace() function

and try something like

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

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

Upvotes: 1

allen213
allen213

Reputation: 2277

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

Upvotes: 1

vinculis
vinculis

Reputation: 473

This should work for you:

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

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

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

Upvotes: 0

flowfree
flowfree

Reputation: 16462

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

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

Upvotes: 8

Related Questions