Home > Software design >  How to check if file (separated by line) has specific word?
How to check if file (separated by line) has specific word?

Time:01-07

I have this file named test.txt and this are the content which are separated by linebreak (** \r\n **)

9ASB3B5B6SDF/1123 WZSB542BD6SD/2255 7SDB3B5B6SDF/3345 FK3B5B6SDFHJ/3434

How can i for example check the test.txt file has if FK3B5B6SDFHJ/3434 inside it?

Here's what i tried but didn't work:

    $file = file_get_contents('file.txt');
    $searchfor = "FK3B5B6SDFHJ/3434\r\n";
if(strpos($file, $searchfor)) {
    $status = 'already exist';
}else{
    $status = 'does not exist'
}

i also tried just searching for FK3B5B6SDFHJ/3434 and FK3B5B6SDFHJ with strpos() but it didn't work either.

CodePudding user response:

My personal advice is to use PHP_EOL to avoid headaches regarding different OS carriage return:

$file = file_get_contents('file.txt');
$codes = explode(PHP_EOL, $file);
$searchfor = "FK3B5B6SDFHJ/3434";
if(in_array($searchfor, $codes)) {
    $status = 'already exist';
}else{
    $status = 'does not exist';
}

CodePudding user response:

You can easily find if the content of your file contains your needle with strpos or str_contains if you have PHP>=8

$fileContent =
"9ASB3B5B6SDF/1123
WZSB542BD6SD/2255
7SDB3B5B6SDF/3345
FK3B5B6SDFHJ/3434";

$searchfor = 'FK3B5B6SDFHJ/3434';

if(strpos($fileContent, $searchfor) !== false) {
    $status = 'already exist';
}else{
    $status = 'does not exist';
}

echo $status;

CodePudding user response:

Use file() and in_array()

An alternative to file_get_contents is the file function which directly returns the file contents as an array. Make sure to use the correct line endings for the OS that PHP runs in.

You can then easily check using in_array. Links to documentation below.

$lines = file('file.txt');
$searchfor = "FK3B5B6SDFHJ/3434";
if(in_array($searchfor, $lines)) {
  $status = 'already exist';
}else{
  $status = 'does not exist';
}

Links

  • Related