我需要替換和concat一些隨機字符串中的值,我將值存儲在一個數組中。PHP替換和concat
I.e.
$search = array('dog', 'tree', 'forest', 'grass');
$randomString = "A dog in a forest";
如果一個或多個陣列值隨機字符串相匹配的話,我需要更換這樣的:
$replacedString = "A @dog in a @forest";
有人能幫助我嗎?
Thx。
我需要替換和concat一些隨機字符串中的值,我將值存儲在一個數組中。PHP替換和concat
I.e.
$search = array('dog', 'tree', 'forest', 'grass');
$randomString = "A dog in a forest";
如果一個或多個陣列值隨機字符串相匹配的話,我需要更換這樣的:
$replacedString = "A @dog in a @forest";
有人能幫助我嗎?
Thx。
這應該爲你工作:
$words = explode(" ", $randomString);
foreach($words as $word){
if(in_array($word, $search)){
$word = "@$word";
}
}
$replacedString = implode(" ", $words);
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);
閱讀文檔[str_replace](ht tp://php.net/manual/fr/function.str-replace.php)。 – Yohann