Steeven
Steeven

Reputation: 4200

Get entire text line that starts with search pattern

I have a .txt file full of lines that each start with a unique id in square brackets:

[13] Text text text text text text text
[23] Text text text text text text text
[65] Text text text text text text text
[07] Text text text text text text text 
[66] Text text text text text text text

With php I open and retrieve the text file content:

$file = 'path_to_file/file.txt';
$handle = fopen($file, "r");
$content = fread($handle, filesize($file));
fclose($handle);

$search_id = '[65]';

I now wish to find the individual line in $content that starts with the id I am searching for ($search_id), and retrieve only that line. The id's in square brackets (followed by a space) will always initiate the lines. When retrieving the line, I wish to strip it of this id, since I only need the text line without the id.

My questions are:

Upvotes: 0

Views: 73

Answers (3)

user2342558
user2342558

Reputation: 6703

First of all, I suggest you use file to get an array containing the file's lines:

$file = 'path_to_file/file.txt';

$search_id = '[65]';

$lines = file($file);

$text = $textWithSearchId = '';
foreach($lines as $line)
{
    if(strpos(trim($line), $search_id) === 0)
    {
        $text = trim(substr($line, strlen($search_id)));
        $textWithSearchId = $line;
    }
}
echo "$text<br />$textWithSearchId";

Here is a working test:

$lines = array();
$lines[] = "[13] Text 13 text text text text text text";
$lines[] = "[23] Text 23 text text text text text text";
$lines[] = "[65] Text 65 text text text text text text";
$lines[] = "[07] Text 07 text text text text text text";
$lines[] = "[66] Text 66 text text text text text text";

$search_id = '[65]';

$text = $textWithSearchId = '';
foreach($lines as $line)
{
    if(strpos(trim($line), $search_id) === 0)
    {
        $text = trim(substr($line, strlen($search_id)));
        $textWithSearchId = $line;
    }
}
echo "$text<br />$textWithSearchId";

Output:

Text 65 text text text text text text
[65] Text 65 text text text text text text

Upvotes: 0

ankit singh
ankit singh

Reputation: 575

$file = 'path_to_file/file.txt';
$handle = fopen($file, "r");
$content = fread($handle, filesize($file));
fclose($handle);
$arr = explode(PHP_EOL, $content);
$search_id = '[65]';
foreach ($arr as $value) {
    $result = substr($value, 0, 4);
    if($result === $search_id) 
    {
      $string = str_replace($search_id,'', $value);
      print_r($string);
      return;
    }
}

Variable $string contains the output

Upvotes: -1

AbraCadaver
AbraCadaver

Reputation: 78994

If the files aren't enormous, and since you're already reading the entire file, you can use a Regular Expression:

$id = "07";
preg_match("/\[$id\] (.*)/", file_get_contents($file), $match);
echo $match[1];
  • Match [$id] and then a space and then match everything else and capture it (.*)

Upvotes: 2

Related Questions