用 php & 替换文本中的关键字mysql
我有一个新闻网站,其中包含超过 100 万条新闻的档案。 我创建了一个包含大约 3000 个条目的单词定义数据库,其中包含单词定义对。
我想做的是在新闻中每次出现这些词的旁边添加一个定义。 我无法进行静态更改,因为我每天都可以添加新关键字,因此我可以使其实时或缓存。
问题是,str_replace
或 preg_replace
在文本中搜索 3000 个关键字并替换它们会非常慢。
有没有快速的替代方案?
I have a news site containing an archive with more than 1 million news.
I created a word definitions database with about 3000 entries, consisting of word-definition pairs.
What I want to do is adding a definition next to every occurence of these words in the news.
I cant make a static change as I can add a new keyword everyday, so i can make it realtime or cached.
The question is, a str_replace
or a preg_replace
would be very slow for searching 3 thousand keywords in a text and replacing them.
Are there any fast alternatives?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
str_replace 不适用于您(除非您希望“superlative”中的“perl”成为关键字),您需要考虑单词边界的东西(例如 preg_replace 与
\b
)。当然,你不能一次preg_replace所有3000个关键字,但一个文档很难包含所有这些关键字,因此我建议对所有文档进行预索引,例如维护一个索引表doc_id->word_id。在提供特定文档时,查询索引并仅替换文档实际包含的关键字(大概不超过 100 个)。另一方面,如果文档很短,那么维护索引表可能就不值得了。您可以简单地即时进行预索引,例如使用
strpos
:str_replace won't work for you (unless you want "perl" in "superlative" to be a keyword), you need something that takes word boundaries into account (e.g. preg_replace with
\b
). Of course, you cannot preg_replace all 3000 keywords at once, but one single document can hardly contain them all, therefore I'd suggest pre-indexing all documents, for example, by maintaining an index table doc_id->word_id. When serving a specific document, query the index and only replace keywords that the document actually contains (presumably no more than 100).On the other side, if documents are short, maintaining the index table might not be worth the trouble. You can simply do pre-indexing on the fly, e.g. with
strpos
:str_replace 非常快速,据我所知,它是 PHP 中最快的。你当然应该保留一个缓存;这将绕过性能问题。
str_replace is pretty zippy and is, to my knowledge, the fastest you will find for PHP. You should certainly keep a cache; that will bypass performance issues.
这只是一个加快流程、减少错误等的建议。
this is just a suggestion to speed up the process, reduce errors etc.