Solved

inserting a string after a certain line using php...

Posted on 2013-01-02
12
372 Views
Last Modified: 2013-01-04
I have a text file as follows;

[context]
user=test;
user2=test2
password=secret
ipaddress: 192.x.x.x

I need to add new lines (host=ipaddress.com)after the string [context]. Can someone let me know how this can be done? I am trying to use someting line the following code, thank you.

A

 
<?php
    $fp = fopen('/file.txt', 'a+');
    fseek($fp, 2, SEEK_SET); 
    fwrite($fp, $newLine."\n");
    fclose($fp);
?>

Open in new window

0
Comment
Question by:aej1973
  • 6
  • 3
  • 2
  • +1
12 Comments
 
LVL 12

Assisted Solution

by:adrian_brooks
adrian_brooks earned 100 total points
ID: 38738635
Untested, but give this a try;

<?php
  $fp = fopen('/file.txt', 'r') or die("Could not open file for reading\n");
  $linedata = array();
  $line_num = 0;
  while(!feof($fp) {
    $line = fgets($fp);
    i($line_num == 1) {
      array_push($linedata, "My new line of text\n");
    } else {
      array_push($linedata, $line);
    }
  }
  fclose($fp);

  $fp2 = fopen('/target.txt', 'a+') or die("Could not open file for writing\n");
  $file_body = impode("\n", $linedata);
  fwrite($fp2, $file_body);
  fclose($fp2);
?>

Open in new window

0
 

Author Comment

by:aej1973
ID: 38738704
adrian_brooks, thank you. Now what do I do if  [context] is not the first line of the text file but is somewhere between the file?
0
 
LVL 12

Expert Comment

by:adrian_brooks
ID: 38738795
Well, simply swap out the "if($line_num == 1) {" conditional with this;
if(preg_match('/\[context\]/m', $line)) {

This will then fire only when it encounters that exact text match. :)
0
Is Your AD Toolbox Looking More Like a Toybox?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

 

Author Comment

by:aej1973
ID: 38738815
Thank you, I will try this.
0
 
LVL 12

Expert Comment

by:adrian_brooks
ID: 38738824
Best of luck to you. :)
0
 

Author Comment

by:aej1973
ID: 38738940
adrian, why do you have two files; file.txt,target.txt? I am working with only one file that has the date that needs to be manipulated ( data.txt). Please let me know, thank you.

A
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 38739653
@aej1973: Please get the file that has your test data, and upload it to EE so we can show you how it works.  If you don't have any test data yet, please create some.  

http://sscce.org/

Thanks, ~Ray
0
 
LVL 34

Accepted Solution

by:
gr8gonzo earned 200 total points
ID: 38739723
@aej1973 - in a previous question, you had a line that started with "register => " instead of "register = " and now I see a colon used as an assignment after "ipaddress" - is this actually correct data? It seems really strange that you'd have varying formats inside the same file, which looks like a normal INI file (which could be parsed easily with the parse_ini_file() function):

http://php.net/manual/en/function.parse-ini-file.php

Also, in your previous question, you used file_get_contents() and explode() to get the file contents in an array of lines (by the way, you can use file() to do the same thing in one line), so I'm wondering why you're using a different approach now.
0
 

Author Comment

by:aej1973
ID: 38740148
Hello gr8gonzo, you are right I was trying a different approach. I did not get a chance to work on it last night but will be working on this module shortly, I will keep you posted on the exact data and the outcome of my tests. Thank you for all your assistance.

A
0
 

Author Comment

by:aej1973
ID: 38740592
gr8gonzo, thank you, your suggestion worked! Please let me know if this looks ok, the output of this code give my desired result. Thank you.

A
$file = 'extensions.txt';
        $txt = file_get_contents($file); //converts a file to a string
        $Blocks = explode(PHP_EOL, $txt); //puts file in an array
        $pLine="[users]";
		$location=array_search($pLine,$Blocks)+1;
		echo $location;
		$data="exten=>this is a new line";
		array_splice( $Blocks,$location , 0, $data ); 
		$txt = implode("\n", $Blocks);
        file_put_contents($file, $txt);

Open in new window

0
 
LVL 34

Expert Comment

by:gr8gonzo
ID: 38740823
Looks fine to me. I would probably recommend using file() and a couple of inline values just to avoid the creation of extra variables that don't really serve another purpose:

$file = 'extensions.txt';
$blocks = file($file);
$location=array_search("[users]",$blocks)+1;
$data="exten=>this is a new line";
array_splice($blocks,$location , 0, $data );
file_put_contents($file, implode("\n", $blocks));
0
 

Author Comment

by:aej1973
ID: 38745492
gr8gonzo, thank you.
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

773 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question