如何考虑字符串的所有字母/键,而不是该字符串的部分值/字母?

时间:2017-06-02 04:49:55

标签: random preg-match implode strtr

$myVar = 'essa pizza é muito gostosa';

$myWords=array(
    array('sabor','gosto','delicia'),
    array('saborosa','gostosa','deliciosa'),
);

foreach($myWords as $words){
    // randomize the subarray
    shuffle($words);
    // pipe-together the words and return just one match
    if(preg_match('/\b\K'.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;

应替换为:

$myVar = 'essa pizza é muito deliciosa';

$myVar = 'essa pizza é muito saborosa';

但是您正在交易较小的单词键,只是因为这个较小的键还包含这个较大键的所有字母!

输出正在发生错误:

$myVar = 'essa pizza é muito saborsa';

" saborsa" 这个词在Portugues中不存在,在我的数组中也是如此)!

正在切断" gostosa"这个词,并将#34; sabor" 然后,而不是输入" saborosa,"正在形成一个不存在的词:" saborsa" 。单词" gostosa" =" sa" + word" sabor" =" saborsa" (这个词不存在)必须是" saborosa"。

最大的问题是要考虑" gostosa" 这个词的一部分作为单词" gosto"

如何在更换之前阅读完整的密钥/字? 感谢

1 个答案:

答案 0 :(得分:1)

这只是一个写得不好的字边界问题。 wordboundaries只应用于第一个备选方案的开头和最后一个备选方案的结尾。

$_POST['Submit']

输出:

$myVar = 'essa pizza é muito gostosa';

$myWords=array(
    array('sabor','gosto','delicia'),
    array('saborosa','gostosa','deliciosa'),
);

foreach($myWords as $words){
    // randomize the subarray
    shuffle($words);
    // 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;