【问题标题】:PHP - str_replace not workingPHP - str_replace 不起作用
【发布时间】:2013-08-14 14:20:54
【问题描述】:

我正在尝试从文件中删除包含在 .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 循环遍历数组。

【问题讨论】:

  • 你能分享一下 worldmap.js 包含的内容吗?如果可能,只保留文件的一部分。

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


【解决方案1】:

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

更改下一行

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

与这些

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

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

【讨论】:

  • 这就是修复它的原因。非常感谢。这就是我讨厌使用 PHP 的原因;这么多错误都是这样的小事。
  • 不客气。我认为这不是 PHP 的问题,它的操作系统处理问题(Window 和 Linux 制定了自己的规则)。
【解决方案2】:

无法复制。

<?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()。但是,替换工作正常,如果仍然无法正常工作,您的文本文件可能是问题所在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-23
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多