首页 > 解决方案 > 用另一个词替换单词 - 搜索和替换是红色的数组

问题描述

这是我之前提出的问题的后续问题:

我试图在一个家谱程序中替换一个人的已婚头衔。喜欢:“用女性版本替换最后姓氏字符串中的标题”。标题是 $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})";

它工作......部分。但是,我仍然有一个问题:仅当 original_title 和 replacement_title 位于 csv 中的 [0] 和 [1] 时,它才会替换标题 - 如果该对是 [2] 和 [3],或者 [4] 和 [5 ] ...尽管通过“while”进行迭代

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

......导致类似“Marie Louise Freiherr von Hardtenstein(nee Becker)”而不是“Marie Louise Freiherrin von Hardtenstein(nee Becker)”......

标签: phparrayscsvreplacewhile-loop

解决方案


这是因为您需要将您的$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})";

推荐阅读