PHP str_替换存储在文本文件中的数组
我试图使用PHP的PHP str_替换存储在文本文件中的数组,php,arrays,str-replace,Php,Arrays,Str Replace,我试图使用PHP的str_replace替换基于两个数组的字符串,这两个数组都存储在外部文本文件中 //All codes listed in a txt file $codes = file('aircodes.txt'); //Full name replacements $full = file('fullcodes.txt'); $string = "BUF YUL YYZ"; $newstring = str_replace($codes, $full, $string); ec
str_replace
替换基于两个数组的字符串,这两个数组都存储在外部文本文件中
//All codes listed in a txt file
$codes = file('aircodes.txt');
//Full name replacements
$full = file('fullcodes.txt');
$string = "BUF YUL YYZ";
$newstring = str_replace($codes, $full, $string);
echo $newstring;
我的aircodes.txt文件的内容:
BUF
YUL
YYZ
Buffalo
Montreal
Toronto
我的fullcodes.txt文件的内容:
BUF
YUL
YYZ
Buffalo
Montreal
Toronto
尽管如此,我的代码没有一个被城市名称取代。如果我从每个文本文件中删除了除一行以外的所有内容,它就会工作。这是因为除了最后一行之外,每个元素中还有一个新行字符(意味着在字符串中找不到:BUF\n
或YUL\n
,但是YYZ
)。所以只需附加一个忽略这些字符,如下所示:
$codes = file('aircodes.txt', FILE_IGNORE_NEW_LINES);
//... ^^^^^^^^^^^^^^^^^^^^^ See here
$full = file('fullcodes.txt', FILE_IGNORE_NEW_LINES);
如果执行var\u转储($code)
,也可以看到字符:
FILE\u IGNORE\u NEW\u行