我一直试图从使用php中的file()函数从文本文件创建的数组中提取特定的单词。
文本文件sample.txt如下所示:
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
现在我已经使用file()函数将这个文本文件放入一个数组中。
$file_name='sample.txt';
$file_array=file($file_name);
然后遍历循环以提取每个值并从该数组中搜索单词,例如'Name'。
$data1='Name';
foreach($file_array as $value){
if(stripos($value,$data1)===FALSE)
echo "Not Found";
else
echo "Found";
}
但是它总是打印'Not Found'。我试过使用strpos,strstr, preg_match,但无济于事。此外,如果我使用普通的单词数组而不是从文件创建,它可以正常工作。
Thanks in Advance.
Update:我在这个问题中的目标是首先检测它是什么字段。'Name'和它的值ex。"测试"
这当然可能是行结束问题或文件编码问题,我不确定file()究竟如何处理空白。
作为如何改进代码的建议,如果您从数据中创建自己的键数组,那么您可以使用更可靠的array_key_exists()函数来搜索您的字段。
$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]);
}
现在你可以这样使用array_key_exists:
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'];
}
很可能在数组中每个"行"的末尾仍然有换行符。试着这样加载:
$file_array=file($file_name, FILE_IGNORE_NEW_LINES);