0

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.

1
  • READ the doc of str_replace please. Commented May 28, 2012 at 10:26

4 Answers 4

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

echo $replacedString;  // A @dog in a @forest
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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);

Comments

0

This should work for you:

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

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.