用另一个单词替换单词-搜索并替换为红色的数组

时间:2019-10-18 12:15:48

标签: php arrays csv replace while-loop

这是我先前提出的一个后续问题:

我试图用家谱程序代替一个人的已婚头衔。 例如:“将标题替换为女性版本末尾的姓氏字符串”。 标题是$ mpref。在CSV中是男性标题(用于查找)和女性标题(用于替换):

            $mpref = trim($mpref);
            $file = fopen("mods/m_replace.csv","r");

            while (($csv = fgetcsv($file)) !== false) {
                $search = array();
                $replace= array();
                $search = $csv[0];
                $replace = $csv[1];
            }
            fclose($file);
            $blub = str_replace($search, $replace, $mpref);
            $lastname = "{$blub} {$mName} ({$text['nee']} {$lastname})";

它部分地起作用。但是,我仍然有一个问题: 仅当csv中的original_title和replace_title分别位于[0]和[1]时,才替换标题-如果该对是[2]和[3]或[4]和[5] ...则不替换标题,尽管通过“而“

e.g. from csv:
Herzog, Herzogin
Freiherr, Freiherrin
Graf, Gräfin

...导致出现类似“玛丽·路易斯·弗赖海尔·冯·哈登斯坦(nee Becker)”的故事,而不是“玛丽·路易斯·弗雷尔林·弗雷尔海姆冯·哈登斯坦(nee Becker)”……

1 个答案:

答案 0 :(得分:0)

这是因为您需要将$search$replace数组初始化移到while循环之外。

            $mpref = trim($mpref);
            $file = fopen("mods/m_replace.csv","r");
            $search = array();  //Define before the loop
            $replace = array(); //Define before the loop

            while (($csv = fgetcsv($file)) !== false) {
                //$search = array();    //Commented this as it should be outside the loop.
                //$replace= array();    //Commented this as it should be outside the loop.
                $search[] = $csv[0];    //Add Value to Array. See the []
                $replace[] = $csv[1];   //Add Value to Array. See the []
            }
            fclose($file);
            $blub = str_replace($search, $replace, $mpref);
            $lastname = "{$blub} {$mName} ({$text['nee']} {$lastname})";
相关问题