简体   繁体   中英

PHP - str_replace not working

I am trying to remove a list of words, which I have contained in a .txt, from a file. To do this I am reading both files using file_get_contents into strings and using 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:

AD Andorra
BE Belize
etc.

..which is why I am using explode() to strip the country tag.

When I echo $map the string contains all the countries even thought str_replace hasn't thrown an error. 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.

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.

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() . However, the replacement is working fine, if it still doesn't work your text files might be the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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