我有以下两个变量/字符串:
$article = ('Perfume is a mixture of fragrant word1 and aroma complexes, which can be applied to the human body, animals, word2, objects, and living spaces in order to give off a pleasant word3.');
$words = '{word1|word2|word3|word4|word5}';
我需要做的是搜索$ article中$ word中的任何单词,如果发现随机替换$ article中的单词,则从$ word中随机选取单词。
我该怎么办呢?
答案 0 :(得分:3)
如果您需要以相同的格式保留所有内容;
$article = ('Perfume is a mixture of fragrant word1 and aroma complexes, which can be applied to the human body, animals, word2, objects, and living spaces in order to give off a pleasant word3.');
$words = '{word1|word2|word3|word4|word5}';
$words = explode('|', str_replace(array('{', '}'), '', $words));
echo str_replace($words, $words[array_rand($words)], $article);
答案 1 :(得分:0)
创建一个$ words数组。获取数组的随机键,并使用随机选择的单词str_replace $ article。
$words = array('word1', 'word2', 'word3', 'word4');
$randkeyA = array_rand($words);
$randkeyB = array_rand($words);
echo str_replace($words[$randkeyA], $words[$randkeyB], $article);