简体   繁体   English

PHP-str_replace无法正常工作

[英]PHP - str_replace not working

I am trying to remove a list of words, which I have contained in a .txt, from a file. 我正在尝试从文件中删除包含在.txt中的单词列表。 To do this I am reading both files using file_get_contents into strings and using str_replace. 为此,我正在使用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;

The "countries.txt" contains the countries in this format: “ countries.txt”包含以下格式的国家/地区:

AD Andorra
BE Belize
etc.

..which is why I am using explode() to strip the country tag. ..这就是为什么我使用explode()剥离国家标签的原因。

When I echo $map the string contains all the countries even thought str_replace hasn't thrown an error. 当我回显$ map时,该字符串包含所有国家,甚至认为str_replace都没有抛出错误。 I have tried printing out $country to confirm it's reading the countries correctly along with reading it into an array and then looping through the array, using str_replace. 我尝试打印出$ country,以确认它正确读取了国家/地区,并将其读入数组,然后使用str_replace遍历该数组。

I think you need some modification in code 我认为您需要对代码进行一些修改

change below line 在行下更改

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

to with these 与这些

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

As you are working on window which uses \\r\\n for new line. 当您在使用\\r\\n作为新行的窗口上工作时。

Cannot reproduce. 无法复制。

<?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);

Output: 输出:

string(1) " "

The space is expected, if you want to get rid of it use trim() . 如果您想摆脱空间,请使用trim() However, the replacement is working fine, if it still doesn't work your text files might be the problem. 但是,替换工作正常,如果仍然无法正常工作,则可能是文本文件出现问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM