Search word in text Php

0

I have a text file named 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 display only the first line:

<ID>490901</ID>

File in php:

<?php

$search = '<ID>';

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

?>

But my script in php gives me the following result:

490901 28602 298174 1081022

How do I get only 490901 ?

    
asked by anonymous 24.01.2017 / 14:47

3 answers

1

If there is no reason for you to go through all the lines of the file, just as 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, searching for all the lines of the file, just give a 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;
    }
} ?>
    
24.01.2017 / 15:03
0

This is because all rows ( $line ) have <ID> (from $search ).

If you just want to get what contains 490901 you can use:

$search = '490901';

Doing only this change would just work:

<ID>490901</ID>

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

When you use:

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

}

You are telling to do something whenever there is <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 value of the array.

<?php

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

?>

This will result in:

<ID>490901</ID>
    
24.01.2017 / 15:03
0

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

For example:

$search = '490901';

Replace if inside foreach with:

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

Or, you can leave the way you are and put the break after the first echo.

Now I have a question: the value you want will always be in the first line or value searched can be anywhere in the file? For if it is always the first line, there are easier methods to get this value.

    
24.01.2017 / 15:04