Solved

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

Posted on 2013-01-02
12
371 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
 

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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 108

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Permalink issue in Wordpress archive 1 32
AWS EC2 PHP code is not being executed code shows on the page instead 8 65
Echo images using file system 2 29
Php pie charts 3 26
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
These days socially coordinated efforts have turned into a critical requirement for enterprises.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
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 …

930 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now