1

This is my first post on the internet for some assistance with coding so please bear with me! I have been finding open code on the internet for a few years and modding it to do what I want but I seem to have come up against a wall with this one that I am sure is very simple. If you would please be able to help me it would be very much appreciated.

I have the following page:

    <?php 
    $text = $_REQUEST['message'];
    $f = file_get_contents("all.txt"); 
    $f = explode(", ", $f); 

    function modFile($pos, $tothis, $inthis)
    { 
        foreach($inthis as $pos => $a){ 
        } 
        $newarr = implode("\r\n", $inthis); 
        $fh = fopen("example.txt", "w"); 
        fwrite($fh, $newarr); 
        fclose($fh); 
    } 

    modFile(4, '', $f); 

I have a file (all.txt) with the following:

    11111111111, 22222222222, 33333333333, 44444444444

That I wish to display like this:

    11111111111 
    22222222222
    33333333333
    44444444444

and to add a space then some text after each number where the text is the same on each line:

    11111111111 text here
    22222222222 text here
    33333333333 text here
    44444444444 text here

I have an html form that passes the custom text to be appended to each line. I need to keep the file all.txt intact then save the newly formatted file with a different name.

I have tried putting variables into the implode where I currently have the "\r\n" but this does not work.

Any help very much appreciated.

Thanks in advance!

Gordon
  • 312,688
  • 75
  • 539
  • 559
Martyn
  • 73
  • 1
  • 3
  • 14

2 Answers2

2

A few notes about your code: You are passing $pos to the function but it will get overwritten in the foreach. Also the foreach is empty, so what's it good for? And I don't see you use $text anywhere either.

To achieve your desired output, try this instead:

file_put_contents(
    '/path/to/new.txt',
    preg_replace(
        '/[^\d+]+/',
        ' some text' . PHP_EOL,
        file_get_contents('all.txt')
    )    
);

The pattern [^\d+]+ will match any string that is not a consecutive number and replace it with "some text " and a new line.

A somewhat more complicated version achieving the same would be:

file_put_contents(
    '/path/to/new.txt', 
    implode(PHP_EOL, array_map(
        function ($number) {
            $message = filter_var(
                $_POST['message'], FILTER_SANITIZE_SPECIAL_CHARS
            );
            return sprintf('%s %s', trim($number), $message);
        },
        array_filter(str_getcsv(file_get_contents('/path/to/all.txt')))
    )
));

This will (from the inside out):

  • Load the content of all.txt and parse it as CSV string into an array. Each array element corresponds to a number.
  • Each of these numbers is appended with the message content from the POST superglobal (you dont want to use REQUEST).
  • The resulting array is then concatenated back into a single string where the concatenating character is a newline.
  • The resulting string is written to the new file.

In case the above is too hard to follow, here is a version using temp vars and no lambda:

$allTxtContent = file_get_contents('/path/to/all.txt');
$numbers = array_filter(str_getcsv($allTxtContent));
$message = filter_var($_POST['message'], FILTER_SANITIZE_SPECIAL_CHARS);
$numbersWithMessage = array();
foreach ($numbers as $number) {
    $numbersWithMessage[] = sprintf('%s %s', trim($number), $message);
};
$newString = implode(PHP_EOL, $numbersWithMessage);
file_put_contents('/path/to/new.txt', $newString);

It does the same thing.

Community
  • 1
  • 1
Gordon
  • 312,688
  • 75
  • 539
  • 559
  • Gordon, Many thanks for this - it works! It does however leave one further instance of the message text at the end of the file. Any ideas? Maybe there is an extra space kicking around somewhere. In relation to my code, as I say I was modding existing code I found and left some bits in that were obviously not necessary. I thank you very much for your assistance! – Martyn Aug 11 '12 at 12:30
  • @user1592162 there is probably a dangling comma after the last number in all.txt. Either remove it or put an `if` into the anonymous function checking whether `$number` is empty or put an `array_filter` around the `strgetcsv` call. – Gordon Aug 11 '12 at 12:31
  • Cheers. Is it possible to have a second variable passed to the script from the html form called 'time'? I need to modify the path of the place where the new file is stored to include the time eg: folder/$time/example.txt Many thanks in advance. – Martyn Aug 11 '12 at 12:42
  • @user yes, easily. after you made sure that $time is in the desired format, just change the path to the new file to read `"/path/to/folder/$time/example.txt"` – Gordon Aug 11 '12 at 12:46
  • I tried that before I asked but it won't pull across the variable from the html page. Do I call it with $time = $_REQUEST['time']; ? I am not using php to get the time as the user is entering the hour at which something is to be filed to be called later you see. Hope this makes sense - thanks again! – Martyn Aug 11 '12 at 12:50
  • I have tried the following with no success: Sorry can't seem to format the code correctly in this comment box. – Martyn Aug 11 '12 at 12:57
  • Warning: file_put_contents($time/example.txt) [function.file-put-contents]: failed to open stream: No such file or directory in C:\wamp\www\sms\create_schedule.php on line 11 It seems that the value of the variable is not displaying but the name or it ($time) is. Thanks again for your help - it is much appreciated! – Martyn Aug 11 '12 at 13:04
  • @user1592162 change the single quotes to double quotes. you want to do [string interpolation](http://de2.php.net/manual/de/language.types.string.php#language.types.string.parsing). – Gordon Aug 11 '12 at 13:05
0

Your foreach() closing brace is on the wrong place. You've missed the exact part of running the execution of the new file creation. Here:

$text = $_REQUEST['message'];
$f = file_get_contents("all.txt"); 
$f = explode(", ", $f);
function modFile($pos, $tothis, $inthis, $text){ 
    $fh = fopen("example.txt", "w");
    foreach($inthis as $pos => $a){ 
        $newarr = $a." ".$text."\r\n";
        fwrite($fh, $newarr);
    }
    fclose($fh);
} 
modFile(4, "", $f, $text);

This is for formatting your new file as you desire, however, you're not passing the new $text['message'] you want to append to your new file. You could either modify your mod_file() method or pass it within the foreach() loop while it runs.

EDIT* Just updated the whole code, should be now what you aimed for. If it does, please mark the answer as accepted.

Xhezairi
  • 544
  • 6
  • 17
  • there is no point in passing `$pos` to `modFile` when you overwrite it in the `foreach`. Also newlines are platform dependent. You will want to use `PHP_EOL` instead. – Gordon Aug 11 '12 at 12:37