我知道標題與其他問題類似,但我找不到要找的內容。PHP從字符串中替換一個隨機單詞並替換爲變量
我有一個變量,說:
$myVar = 'bottle';
而且,當時我有一個字符串:
$myString = 'Hello this is my string';
我需要一些代碼來選擇一個隨機單詞的$myString
與$myVar
更換。我怎樣才能做到這一點?
我知道標題與其他問題類似,但我找不到要找的內容。PHP從字符串中替換一個隨機單詞並替換爲變量
我有一個變量,說:
$myVar = 'bottle';
而且,當時我有一個字符串:
$myString = 'Hello this is my string';
我需要一些代碼來選擇一個隨機單詞的$myString
與$myVar
更換。我怎樣才能做到這一點?
$myVar = "bottle";
$myString = 'Hello this is my string';
$words = explode(" ", $myString);
$words[rand(0, count($words)-1)] = $myVar;
echo join(" ", $words);
你可以只算單詞分隔符(在這種情況下空格),用戶rand
的數量,讓他們隨機一個,那麼就由strpos
與rand
值偏移拿到字的內容(第三個參數),或者只是爆炸數組的字符串(空格),然後再次(空格再次)implode
來替換隨機單詞後的字符串。
這是你所需要的:
$myVar = 'bottle';
$myString = 'Hello this is my string';
$myStringArray = explode(' ', $myString);
$rand = mt_rand(0, count($myStringArray)-1);
$myStringArray[$rand] = $myVar;
$myNewString = implode(' ', $myStringArray);
那麼這個怎麼樣:
$words = explode(' ', $myString);
$wordToChange = rand(0, count($words)-1);
$words[$wordToChange] = $myVar;
$final = implode(' ', $words)
沒有像一個老式的PHP種族:
$myString = 'Hello this is my string';
$myVar = 'bottle';
$words = explode(' ', $myString); // split the string into words
$index = rand(0, count($words) - 1); // select a random index
$words[$index] = $myVar; // replace the word at the random position
$myString = implode(' ', $words); // merge the string back together from the words
你也可以使用正則表達式來執行此操作
$idx = rand(0, str_word_count($myString) - 1);
$myString = preg_replace("/((?:\s*\w+){".$idx."})(?:\s*\w+)(.*)/",
"\${1} $myVar\${2}", $myString);
這會跳過隨機數字並替換下一個單詞。
你可以在行動here看到這個正則表達式。更改大括號內的數字會導致第一個捕獲組消耗更多的單詞。
你爆炸了錯誤的變種。 $ myVar是更換 –
謝謝,回答編輯! – MSadura