我有一个代码将输出与数组的值进行比较,并且只用数组中的单词终止操作:
第一个代码(只是一个例子)
$myVar = 'essa pizza é muito gostosa, que prato de bom sabor';
$myWords=array(
array('sabor','gosto','delicia'),
array('saborosa','gostosa','deliciosa'),
);
foreach($myWords as $words){
shuffle($words); // randomize the subarray
// pipe-together the words and return just one match
if(preg_match('/\K\b(?:'.implode('|',$words).')\b/',$myVar,$out)){
// generate "replace_pair" from matched word and a random remaining subarray word
// replace and preserve the new sentence
$myVar=strtr($myVar,[$out[0]=>current(array_diff($words,$out))]);
}
}
echo $myVar;
我的问题:
我有第二个代码,它不适用于 rand/shuffle(我不想要 rand,我想要精确的替换,我总是将第 0 列更改为 1),是要始终交换值:
// wrong output: $myVar = "minha irmã alanné é not aquela blnode, elere é a bom plperito";
$myVar = "my sister alannis is not that blonde, here is a good place";
$myWords=array(array("is","é"),
array("on","no"),
array("that","aquela"),
//array("blonde","loira"),
//array("not","não"),
array("sister","irmã"),
array("my","minha"),
//array("nothing","nada"),
array("myth","mito"),
array("he","ele"),
array("good","bom"),
array("ace","perito"),
// array("here","aqui"), //if [here] it does not exist, it is not to do replacement from the line he=ele = "elere" non-existent word
);
$replacements = array_combine(array_column($myWords,0),array_column($myWords,1));
$myVar = strtr($myVar,$replacements);
echo $myVar;
// expected output: minha irmã alannis é not aquela blonde, here é a bom place
// avoid replace words slice!
预期输出: minha irmã alannis é not aquela 金发女郎,here é a bom place
// avoid replace words slice! always check if the word exists in the array before making the substitution.
alanne , blnode , elere , plperito
它检查输出是否是真实的单词,它们存在于数组 myWords 中,这样可以避免键入错误,例如:
那4个字不是存在的字,是书写错误。你如何为第二个代码做到这一点?
简而言之,必须通过一个完整的词/键,一个现有的词来进行交换。并且不要使用关键字片段创建一些奇怪的东西!