PHP - str_replace无法正常工作

时间:2013-08-13 05:07:27

标签: php file-get-contents str-replace

我正在尝试从文件中删除我在.txt中包含的单词列表。为此,我使用file_get_contents将这两个文件读入字符串并使用str_replace。

$names = file_get_contents("countries.txt");
$map = file_get_contents("C:\\xampp\\htdocs\\www\\jvectormap\\map\\worldmap.js");

$array = explode("\n", $names);

foreach($array as $val){
    $split = explode(" ", $val);
    $max = count($split);
    $country = "";
    for($x = 1; $x < $max; $x++){
        $country = $country . $split[$x];
        if($x < ($max-1)){
            $country = $country . " ";
        }
    }
    $map = str_replace($country, "", $map);
}
echo $map;

“countries.txt”包含此格式的国家/地区:

AD Andorra
BE Belize
etc.

..这就是我使用explode()去除国家标签的原因。

当我回显$ map时,字符串包含所有国家,甚至认为str_replace没有抛出错误。我已经尝试打印$ country以确认它正确读取国家/地区并将其读入数组然后使用str_replace循环遍历数组。

2 个答案:

答案 0 :(得分:1)

我认为您需要对代码进行一些修改

更改行

 $array = explode("\n", $names);

与这些

$names = nl2br($names);
$array = explode("<br />", $names);

正在处理使用\r\n换行的窗口。

答案 1 :(得分:0)

无法重现。

<?php
/* Instead of loading countries.txt */
$names = "AD Andorra
BE Belize";
$array = explode("\n", $names);
/* Instead of loading map */
$map = "Andorra Belize";

$array = explode("\n", $names);

foreach($array as $val){
    $split = explode(" ", $val);
    $max = count($split);
    $country = "";
    for($x = 1; $x < $max; $x++){
        $country = $country . $split[$x];
        if($x < ($max-1)){
            $country = $country . " ";
        }
    }
    $map = str_replace($country, "", $map);
}
var_dump($map);

输出:

string(1) " "

如果您想摆脱它,请使用trim()。但是,替换工作正常,如果它仍然不起作用,您的文本文件可能是问题。