Solved

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

Posted on 2013-01-02
12
370 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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
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

Easy Project Management (No User Manual Required)

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Both Easy and Powerful How easy is PHP? http://lmgtfy.com?q=how+easy+is+php (http://lmgtfy.com?q=how+easy+is+php)  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
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 look for a specific file type in a local or remote server directory using PHP.

744 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

12 Experts available now in Live!

Get 1:1 Help Now