[英]PHP replace sub string with the value from an array
我有一個文字說:
$text = "An Elephant is an Elephant but an Elephant is not an Elephant"
我有一個陣列說:
$array = array("First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eight", "Ninth");
在文中你可以看到有很多出現的“大象”。 我想要做的是我想用數組中的唯一值替換Elephant的出現,結果應該是這樣的:
$result = "An Fifth is an Seventh but an First is not an Fourth"
到目前為止我試過這個:
$arr = array("First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eight", "Ninth");
$text = "an elephant is an elephant but an elephant is not an elephant";
$array = explode(" ", $text);
$new_arr = array_diff($array, array("elephant"));
$text = implode(" ".$arr[array_rand($arr)]." ", $new_arr);
echo $text;
它輸出這樣的東西:
an First is First an First but First an First is First not First an
我怎么能這樣?
An Fifth is an Seventh but an First is not an Fourth
在這,你為什么不嘗試這個?
$arr = array("First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eight", "Ninth");
$arrlength = count($arr);
$text = "an elephant is an elephant but an elephant is not an elephant";
$array = explode(" ", $text);
for ($i=0; $i < count($array); $i++) {
if ($array[$i]=="elephant")
{
$random_key = array_rand($arr, $arrlength);
$array[$i] = $arr[$random_key[rand(0, $arrlength-1)]];
}
}
$text = implode(" ", $array);
echo $text;
這應該適合你:
使用preg_replace_callback()
您可以簡單地使用array_rand()
來始終用數組中的隨機值替換它。
<?php
$arr = array("First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eight", "Ninth");
$text = "an elephant is an elephant but an elephant is not an elephant";
echo $newText = preg_replace_callback("/\belephant\b/", function($m)use($arr){
return $arr[array_rand($arr)];
}, $text);
?>
可能的輸出:
an Seventh is an Third but an First is not an Ninth
適應Rizier123的答案,所以你永遠不會有相同的替代品。 (注意你不需要更換比你陣列中的物品數量更多的物品)
$arr = array("First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eight", "Ninth");
$text = "an elephant is an elephant but an elephant is not an elephant";
echo $newText = preg_replace_callback("/\belephant\b/", function($m)use(&$arr){
$item = array_rand($arr);
$return = $arr[$item];
unset($arr[$item]);
return $return;
}, $text);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.