【问题标题】:replace word with another word - search & replace are red into an array用另一个词替换单词 - 搜索和替换是红色的数组
【发布时间】:2019-10-18 12:15:48
【问题描述】:

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

我试图在一个家谱程序中替换一个人的已婚头衔。 喜欢:“用女性版本替换最后姓氏字符串中的标题”。 标题是 $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] 则不会......尽管通过 "而”

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)”...

【问题讨论】:

  • 我们怎么知道您之前发布的内容??

标签: php arrays csv replace while-loop


【解决方案1】:

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

【讨论】:

  • 嗨 ascsoftw,谢谢。是的,这是一个错误——但不幸的是,这不是解决问题的那个。还有哪些其他问题可能是原因(...)?
  • @Tontaube 请查看最新编辑。循环内的$search 应该是$search[]。 $replace 也一样
  • 知道了! ...我在错误的位置插入了整个段落,因此它被覆盖了...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-02
  • 1970-01-01
  • 2013-10-05
  • 2018-02-24
  • 2011-09-25
  • 2011-09-13
  • 2010-11-05
相关资源
最近更新 更多