PHP:在文本文件中搜索特定短语/单词并输出
我正在尝试制作一个小的 php 脚本来自动化一些工作流程。 该脚本要做的就是读取一个文件(每个文件大约 10-20kb)。 然后我需要在文件中搜索一些特定的短语并输出(如果出现这些短语)行号和短语。
例如,我正在阅读和搜索一个文本文件。我搜索短语“花是黄色的”、“马是白色的”和“混合的”;
那么我的输出是:
第 4 行:“马是白的” 第 19 行:“混合;” 第 22 行:“混合;” 第99行:“花是黄色的” … 等等。
我正在使用这段代码,它可以正确输出每一行和行号,但我无法创建一个仅输出搜索到的短语的搜索例程:
<?php
$lines = file('my-text-file.txt');
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
?>
我的想法是使用 strpos ,然后每次我发现出现了一个短语,它把它放入一个数组(或字典)中,行号作为键,短语作为值,但无法使其工作,我认为可能有更好、更有效的方法方法。
任何我要走的方向的帮助或建议将非常感激。
谢谢
- 梅斯蒂卡
I’m trying to make a small php script to automate some work processes.
What the script has to do is read a file (approximately 10-20kb per file).
Then I need to search the file for some specific phrases and output – if the phrases occur – the linenumber(s) and the phrase.
For example, I’ve a text-file I’m reading and searching within. I search for the phrases “The flower is yellow”, “The horse is white”, and “mixed;”
Then my output is:
Line 4: “The horse is white”
Line 19: “Mixed;”
Line 22: “Mixed;”
Line 99: “The flower is yellow”
… and so on.
I’m using this code, which correctly output each line and the line number but I just can’t make a search routine that only output the searched phrases:
<?php
$lines = file('my-text-file.txt');
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
?>
My though was to use strpos and then every time I find an occurrence of the phrase it put it into an array (or dictionary) which the line number as key and the phrase as value but haven’t been able to make it work and I thought that there might be a better and more effective method.
Any help or suggestions in which direction I’ve to go would be very much appreciated.
Thanks
- Mestika
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
创建一个脚本来 grep 您的输入并将结果通过管道传输到您的 PHP 脚本中。
Create a script that will grep your input and pipe the results into your PHP script.
视频这个:
查找文本文件中的字符串并向该行添加一些内容
Vide this:
Find a string in a text file and add something to that line