The flag on $pos
must be in false
not to include what comes before, taking advantage of your example:
<?php
$text = file_get_contents('animals.txt');
$id = "2";
$id_str = strlen($id);
$pos = stristr($text, $id, false);
$pos_str = strlen($pos);
$pos_str = ($pos_str - $id_str);
$res = substr($pos, $id_str, $pos_str);
echo explode("\n", $res)[0]; // excluir o que vem depois da quebra de linha
Print nothing if not found.
But I think you have more direct and readable ways of doing it, and not so costly. EX:
<?php
$lines = file('animals.txt');
$id = 2;
foreach($lines as $line) {
$params = explode(' ', $line); // dividir cada linha por espaço, id - valor
if($params[0] == $id && isset($params[1])) { // ver se é igual e cobrir a hipotese de poder haver linhas sem o valor (segundo elemento de $params)
$ani = $params[1];
break;
}
}
if(isset($ani)) { // se tivermos encontrado o valor relativo ao id
echo 'Foi encontrado o valor do id ' .$id. ' é: ' .$ani; // COELHO
}
else {
echo 'Nenhum valor para o id ' .$id; // nao encontramos nenhum valor para aquele id
}
What I did here was scroll through each row of the array of all rows, returned by file('animals.txt');
, with each line I divide by space, I keep the array in this format (ex of the first round of the foreach):
$params = array(0 => 0, 1 => 'GATO');
, then compare the $id
we want with each one in position 0
of this array.
If you really want to use file_get_contents
:
<?php
$content = file_get_contents('animals.txt');
$lines = explode("\n", $content); // acrescentar esta linha, dividir por quebra de linha para ficar com todas as linhas num array
$id = 2;
// ... O RESTO É IGUAL AO EXEMPLO ACIMA
I drew, the
file_get_contents
reads the file as a string, while thefile
reads it as array, that’s what I was looking for anyway! Thanks Miguel!– Raizant
Exactly @Jacksonantunes.
file()
return aarray
, in each element is a line. You are welcome– Miguel