Take the 2-minute tour ×

I have a particularly difficult task to complete. I have a PHP script that reads the contents of a file and stores it into a variable. I want to split the text stored by the new line entries and then search the array[0] value for a specific value.

That is my idea. Here is my situation.

I have a directory file with specific entries.


This will be stored into a variable. How do I search this for Entry2 and then get the whole line to work with?


share|improve this question
What have you tried? You'll usually get the best answers on SO if you are more specific. –  liquorvicar Feb 20 '12 at 12:08
add comment

2 Answers

up vote 1 down vote accepted

If you can, use the file() function to load the file into array, already split by newlines:

$lines = file('filename.txt');

If not, you can use

$lines = explode("\n", $contents);

You might want to use \r\n if you're on Windows and file contains CR characters.

To search the array, use foreach:

foreach ($lines as $ix => $line)
    if (strpos ($line, 'string') !== false)
        $lines[$ix] = ...new version of line...

In the end, write contents back to some file:

$fp = fopen('file.txt', 'w+');
foreach ($lines as $line)
    fputs($fp, $line);
share|improve this answer
Windows uses \r\n, not \n\r. –  ComFreek Feb 20 '12 at 12:10
I need to edit this line. When I do so, $lines isn't updated. Help? –  JavaCoder-1337 Feb 20 '12 at 12:31
I updated the answer. –  Milan Babuškov Feb 20 '12 at 15:33
add comment

You could search the directories with RecursiveDirectoryIterator, and search the files contents individually with preg_match_all

share|improve this answer
add comment

Your Answer


