Search word in Php text

Asked

Viewed 3,285 times

0

I have a text file with a name teste.txt, in it I have the following code:

<ID>490901</ID>
<ID>28602</ID> 
<ID>298174</ID> 
<ID>1081022</ID>

I want to create a script to view only the first line:

<ID>490901</ID>

Php file:

<?php

$search = '<ID>';

$lines = file('teste.txt');
foreach($lines as $line)
{
   if(strpos($line, $search) !== false)
    echo $line;
}

?>

But mine script in php me of the following result:

490901 28602 298174 1081022

How can I get just the 490901 ?

  • You can add a break after the echo to stop the execution of foreach after finding the first ID, but should have better ways to do this.

3 answers

1

If there is no reason for you to go through all the lines of the file, just like you are doing, using foreach, why not just print the first line using:

<?php 

$search="<ID>";

$lines = file('teste.txt');
echo $lines[0]; ?>

It would be a possible solution.

Now if you really want to search for the first occurrence of , looking for all lines of the file, just break as soon as you find the first occurrence, as follows:

<?php 
$search="<ID>";

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

foreach($lines as $line) {
    if (strpos($line, $search) !== false) {
        echo $line;
        break;
    }
} ?>

0

This is because all lines ($line) possess <ID> (originating from the $search).

If you just want to get what contain the 490901 you can use:

$search = '490901';

Making only this change would just result:

<ID>490901</ID>

The strpos() finds the position of the first occurrence in the string and if it does not find it will return the false.

When you use:

if(strpos($line, '<ID>') !== false){

}

Are you saying to do something whenever there is the <ID>, in your case ALL LINES have <ID>, so it will return all lines.


If you ALWAYS want to get the first line you can simply use the [0] which is to get the first array value.

<?php

$lines = file('teste.txt');
echo $lines[0];

?>

This will result in:

<ID>490901</ID>

0

You should put in the $search variable the value of the ID you want to search for.

For example:

$search = '490901';

Replaces the if inside the foreach by:

if($line == $search){
    echo $line; // ou $search, pois os dois são o mesmo valor
}

Or you can leave it the way it is and break after the first echo.

Now I have a question: the value you want will always be in the first line or sought value can be in any part of the file? Because if it’s always the first line, there are easier ways to get that value.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.