1

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.

1
  • Can you share what worldmap.js contains. Only a portion of file if possible. Commented Aug 13, 2013 at 5:18

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is what fixed it. Many thanks. This is why I hate working with PHP; so many errors are fiddly little things like this.
You are welcome. I think this is not the problem of PHP, its Operating system handling problem (Window and Linux made their own rules).
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.