PHP 无法搜索从文件创建的数组中的特定单词
我一直在尝试从使用 php 中的 file() 函数从文本文件创建的数组中提取特定单词。
文本文件sample.txt是这样的:
A registration has been received.
Name: test
Lastname: test2
Email: [email protected]
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";
}
但它总是打印“未找到”。我尝试过使用 strpos、strstr、preg_match 但无济于事。另外,如果我使用普通的单词数组而不是从文件创建,它也可以正常工作。
提前致谢。
更新:我在这个问题中的目标是首先检测它是哪个字段。 “名称”,然后是它的值,例如。 '测试'
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: [email protected]
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. 'test'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这当然可能是行结束问题或文件编码问题,我也不确定 file() 如何处理空格。
作为如何改进代码的建议,如果您根据数据创建自己的键控数组,则可以使用更可靠的 array_key_exists() 函数来搜索字段。
现在您可以使用 array_key_exists,如下所示:
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.
Now you can use array_key_exists as follows:
很可能您的数组中每个“行”的末尾仍然有换行符。尝试像这样加载它:
most likely you still have newline characters at the end of each "line" in your array. Try loading it like this: