Reputation: 67
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
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
Reputation: 2277
foreach($search as $word)
{
$randomString = str_replace($word,"@".$word,$randomString);
}
Upvotes: 1
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
Reputation: 16462
foreach (explode(' ', $randomString) as $word) {
$replacedString .= in_array($word, $search) ? "@$word " : "$word ";
}
echo $replacedString; // A @dog in a @forest
Upvotes: 8