开发者

PHP Cant search for specific words in an array created from file

I have been trying to extract specific words from an array which was created from a text file using file() function in php.

The text file sample.txt is like this:

A registration has been received. 

Name: test
Lastname: test2 
Email: test@test.com
Company/School: Test2
Company2: test3
Address1: test4
Address2: test5
City: test6
State: test7
Country: test8
Zipcode: test9

Now I have used file() function to put this text file into an array.

$file_name='sample.txt';
$file_array=file($file_name);

Then I traversed through loop to extract each value and search for word say 'Name' from this array.

    $data1='Name';

    foreach($file_array as $value){
    if(stripos($value,$data1)===FALSE)
        echo "Not Found";
     else 
       echo "Found";
    }

But it always prints 'Not Found'. I have tried using strpos,strstr, preg_match but to no avail. Also if I use a normal array of words instead of creating from file, it works properly.

Thanks in Advance.

Update: My objective in this problem is to first detect what field it is ex. 'Name' and then its value ex开发者_如何学Go. 'test'


It certainly could be a line ending problem or an issue with your file encoding, I'm not sure exactly how file() handles whitespace either.

As a suggestion on how to improve the code, if you create yourself a keyed array from the data then you can use the more reliable array_key_exists() function to search for your fields.

$file_name = 'sample.txt';
$file_data = file($file_name);

// loop through each line
foreach ($file_data as $line) {

// from each line, create a two item array
$line_items = explode(":", $line);

// build an associative (keyed) array
// stripping whitespace and using lowercase for keys
$file_array[trim(strtolower($line_items[0]))] = trim($line_items[1]);
}

Now you can use array_key_exists as follows:

if (array_key_exists("name", $file_array) === false) {
  print "Not found.";
} else {
  print "Found.";  
  // and now it's simple to get that value
  print "<br />Value of name:  " . $file_array['name'];
}


most likely you still have newline characters at the end of each "line" in your array. Try loading it like this:

$file_array=file($file_name, FILE_IGNORE_NEW_LINES);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜