PHP str_replace 数组存储在文本文件中
PHP str_replace array stored in text file
我正在尝试使用 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);
echo $newstring;
我的 aircodes.txt
文件的内容:
BUF
YUL
YYZ
我的 fullcodes.txt
文件的内容:
Buffalo
Montreal
Toronto
不过,我的 none 代码被替换为城市名称。如果我从每个文本文件中删除除一行以外的所有内容,它就可以工作。
这是因为你在最后一个元素中的每个元素中仍然有一个换行符(意味着在你的字符串中它不会找到:BUF\n
或 YUL\n
,但是 YYZ
).所以只要附加一个 flag 来忽略这些字符,就像这样:
$codes = file('aircodes.txt', FILE_IGNORE_NEW_LINES);
//... ^^^^^^^^^^^^^^^^^^^^^ See here
$full = file('fullcodes.txt', FILE_IGNORE_NEW_LINES);
你也可以看到字符,如果你做 var_dump($codes)
:
array(3) {
[0]=>
string(5) "BUF
"
//^ See here new line character
[1]=>
string(5) "YUL
"
//^ See here new line character
[2]=>
string(3) "YYZ"
// ^ See here NO new line character
}
我正在尝试使用 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);
echo $newstring;
我的 aircodes.txt
文件的内容:
BUF
YUL
YYZ
我的 fullcodes.txt
文件的内容:
Buffalo
Montreal
Toronto
不过,我的 none 代码被替换为城市名称。如果我从每个文本文件中删除除一行以外的所有内容,它就可以工作。
这是因为你在最后一个元素中的每个元素中仍然有一个换行符(意味着在你的字符串中它不会找到:BUF\n
或 YUL\n
,但是 YYZ
).所以只要附加一个 flag 来忽略这些字符,就像这样:
$codes = file('aircodes.txt', FILE_IGNORE_NEW_LINES);
//... ^^^^^^^^^^^^^^^^^^^^^ See here
$full = file('fullcodes.txt', FILE_IGNORE_NEW_LINES);
你也可以看到字符,如果你做 var_dump($codes)
:
array(3) {
[0]=>
string(5) "BUF
"
//^ See here new line character
[1]=>
string(5) "YUL
"
//^ See here new line character
[2]=>
string(3) "YYZ"
// ^ See here NO new line character
}