我需要替换和连接随机字符串中的一些值,我将这些值存储在一个数组中。
IE
$search = array('dog', 'tree', 'forest', 'grass');
$randomString = "A dog in a forest";
如果一个或多个数组值与随机字符串匹配,那么我需要这样的替换:
$replacedString = "A @dog in a @forest";
有人能帮我吗?
谢谢。
foreach (explode(' ', $randomString) as $word) {
$replacedString .= in_array($word, $search) ? "@$word " : "$word ";
}
echo $replacedString; // A @dog in a @forest
foreach($search as $word)
{
$randomString = str_replace($word,"@".$word,$randomString);
}
不确定我是否理解您要正确执行的操作,但请查看str_replace()函数
并尝试类似的东西
foreach($search as $string)
{
$replacement[] = "@".$search;
}
$new_string = str_replace($search, $replacement, $randomString);
这应该适合你:
$words = explode(" ", $randomString);
foreach($words as $word){
if(in_array($word, $search)){
$word = "@$word";
}
}
$replacedString = implode(" ", $words);