?
Solved

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

Posted on 2013-01-02
12
Medium Priority
?
376 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 3
  • 2
  • +1
12 Comments
 
LVL 12

Assisted Solution

by:Richard Davis
Richard Davis earned 400 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:Richard Davis
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

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

Expert Comment

by:Richard Davis
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 111

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 35

Accepted Solution

by:
gr8gonzo earned 800 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 35

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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
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 …
Suggested Courses

752 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