SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Addict
    Join Date
    Feb 2004
    Location
    Rome
    Posts
    296
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    add a new line of text after finding a particular string of text in a file using php

    Hello

    how to add a new line of text after finding a particular string of text in a file, using php ?
    Suppose I have the file
    data.txt
    and I want add test after the string @add@ , how to do that ?

    Thank you
    Cris
    trcris ::> http://www.trcris.com

  2. #2
    Foozle Reducer ServerStorm's Avatar
    Join Date
    Feb 2005
    Location
    Burlington, Canada
    Posts
    2,699
    Mentioned
    89 Post(s)
    Tagged
    6 Thread(s)
    Are you reading in the entire text file?
    ictus==""

  3. #3
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    There are many ways of doing this, some better suited that others, here's one.
    Code:
    <?php
    $lines = array();
    foreach(file('source.txt') as $line)
    {
    	if('@add@' === $line)
    	{
    		array_push($lines, 'test');
    	}
    	array_push($lines, $line);
    }
    file_put_contents('source.txt', $lines);
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  4. #4
    SitePoint Addict
    Join Date
    Feb 2004
    Location
    Rome
    Posts
    296
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by AnthonySterling View Post
    There are many ways of doing this, some better suited that others, here's one.
    Code:
    <?php
    $lines = array();
    foreach(file('source.txt') as $line)
    {
    	if('@add@' === $line)
    	{
    		array_push($lines, 'test');
    	}
    	array_push($lines, $line);
    }
    file_put_contents('source.txt', $lines);

    Fantastic , thank you , really of help
    trcris ::> http://www.trcris.com


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •