用另一个单词替换单词-搜索和替换都变成红色数组

问题描述 投票:0回答:1

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

我试图在族谱程序中替换一个人的已婚头衔。例如:“将标题替换为女性版本末尾的姓氏字符串”。标题是$ 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)”的故事,而不是“玛丽·路易斯·[[Freiherrin冯·哈登斯坦(nee·贝克尔)” ......

php arrays csv replace while-loop
1个回答
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]; $replace = $csv[1]; } fclose($file); $blub = str_replace($search, $replace, $mpref); $lastname = "{$blub} {$mName} ({$text['nee']} {$lastname})";

© www.soinside.com 2019 - 2024. All rights reserved.