使用 PHP 在文件中搜索文本
如何使用 PHP 搜索 PDF、doc、docs 或 txt 等文件中的文本? 我想在MySQL中做类似全文搜索的功能, 但这一次,我直接通过文件搜索,而不是数据库。
搜索将在位于文件夹中的许多文件中进行搜索。 对于这个问题有什么建议、技巧或解决方案吗?
我还注意到,谷歌也会搜索这些文件。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
要搜索 PDF,您需要一个像 pdftotext 这样的程序,它将内容从 pdf 转换为文本。对于 Word 文档,可以使用类似的东西(因为 Word 文件中的所有样式和加密)。
一个搜索 PDF 的示例(从我的一个脚本复制(它是一个片段,不是整个代码,但它应该让您有一些理解),我在其中提取关键字并将匹配项存储在 PDF 结果数组中。):
For searching PDF's you'll need a program like pdftotext, which converts content from a pdf to text. For Word documents a simular thingy could be available (because of all the styling and encryption in Word files).
An example to search through PDF's (copied from one of my scripts (it's a snippet, not the entire code, but it should give you some understanding) where I extract keywords and store matches in a PDF-results-array.):
根据文件类型,您应该将文件转换为文本,然后使用
file_get_contents()
和str_pos()
进行搜索。要将文件转换为文本,除了其他工具外,您还可以使用以下工具:catdoc
用于 Word 文件xlhtml
用于 Excel 文件ppthtml
用于 Powerpoint 文件unrtf
用于 RTF 文件pdftotext
用于 pdf 文件Depending on the file type, you should convert the file to text and then search through it using i.e.
file_get_contents()
andstr_pos()
. To convert files to text, you have - beside others - the following tools available:catdoc
for word filesxlhtml
for excel filesppthtml
for powerpoint filesunrtf
for RTF filespdftotext
for pdf files如果您在 Linux 服务器下,您可以使用
exec 从 php 调用,从而导致
If you are under a linux server you may use
called from php using exec resulting in
2021 我遇到了这个并发现了一些东西,所以我想我会链接到它...
注意:docx、pdf 和其他文件不是常规文本文件,需要更多脚本和/或不同的库来读取和/或编辑每种不同类型,除非您可以找到一个全合一的图书馆。这意味着您必须编写要搜索的每种不同文件类型的脚本,尽管包括普通文本文件。如果您不想完全编写脚本,那么您必须安装您想要读取的每种文件类型所需的每个库。但您仍然需要编写每个脚本来将它们作为库函数进行处理。
我在堆栈上此处找到了基本答案。
2021 I came across this and found something so I figure I will link to it...
Note: docx, pdfs and others are not regular text files and require more scripting and/or different libraries to read and/or edit each different type unless you can find an all in one library. This means you would have to script out each different file type you want to search though including a normal text file. If you don't want to script it completely then you have to install each of the libraries you will need for each of the file types you want to read as well. But you still need to script each to handle them as the library functions.
I found the basic answer here on the stack.