Jump to content

Read lines starting with in PHP


vidyashankara

Recommended Posts

[code]
TITLE PHP TEXT
HEADER PHP HEADER
!@##@
123!@#
$#%@#$
sdFSDAF
SDFSDF
[/code]

Lets say we have the above text file, how i select lines starting with TITLE or HEADER? I have the following code currently

[code]
$contents = file_get_contents(file.txt);
$title=  preg_replace('/^(?!TITLE).*?(?:\n|$)/m','',$contents);
[/code]

This does the job, But the script turns up a blank screen now and then because i have 5 of such lines in the script. The preg_replace command is the problem because the script runs really fast when i comment it out. Is there any better way to select lines starting with certain words?
Link to comment
Share on other sites

This might be the long way around it, but it works...
[code]<?php
$file = file("file.txt");
foreach($file as $line)
    if(strpos($line,"TITLE") === 0)
        echo "<p>$line</p>";
?>[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.