php - 用另一个词替换单词 - 搜索和替换是红色的数组
问题描述
这是我之前提出的问题的后续问题:
我试图在一个家谱程序中替换一个人的已婚头衔。喜欢:“用女性版本替换最后姓氏字符串中的标题”。标题是 $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)”......
解决方案
这是因为您需要将您的$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})";
推荐阅读
- swiftui - 将解码的 JSON 数据传递给 SwiftUI ContentView
- python - 用粗体字写出字符串到excel
- qt - 是否可以为 QMLExtensionPlugin 制作 GoogleTest?
- python - Python:为什么 if 语句不会检测变量是大于还是小于 80?
- sql - oracle sql错误:插入blob格式的图片
- python - Flask_Pymongo:如何找到集合?
- fortran - Fortran 中可移植到空流的输出
- docker - Spark 应用程序控制台日志未记录到日志文件
- amazon-web-services - 为什么我将 aws polly 的输出描述为 gibrish?
- ssl-certificate - Traefik - 多个子域的 TLS 证书不起作用