与 PHP strip_tags 等效的 MySQL 查询是什么?
我有一个大型数据库,其中包含带有 标签的记录,我想删除它们。当然,有一种方法是我创建一个 PHP 脚本来选择全部,使用
strip_tags
并更新数据库,但这需要很长时间。那么如何使用简单(或复杂)的 MySQL 查询来做到这一点呢?
I have a large database which contains records that have <a>
tags in them and I would like to remove them. Of course there is the method where I create a PHP script that selects all, uses strip_tags
and updates the database, but this takes a long time. So how can I do this with a simple (or complicated) MySQL query?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
MySQL >= 5.5 提供了 XML 函数来解决您的问题:
参考: https://dev.mysql.com/doc/refman/5.5/en/xml-functions.html
MySQL >= 5.5 provides XML functions to solve your issue:
Reference: https://dev.mysql.com/doc/refman/5.5/en/xml-functions.html
给你:
我确保它删除了不匹配的左括号,因为它们很危险,尽管它忽略了任何不匹配的右括号,因为它们是无害的。
Here you go:
I made sure it removes mismatched opening brackets because they're dangerous, though it ignores any unpaired closing brackets because they're harmless.
我不相信有任何有效的方法可以单独在 MySQL 中做到这一点。
MySQL 确实有 REPLACE() 函数,但它只能替换常量字符串,而不能替换模式。您可以编写一个 MySQL 存储函数来搜索和替换标签,但此时您最好编写一个 PHP 脚本来完成这项工作。它可能不会那么快,但写入速度可能会更快。
I don't believe there's any efficient way to do this in MySQL alone.
MySQL does have a
REPLACE()
function, but it can only replace constant strings, not patterns. You could possibly write a MySQL stored function to search for and replace tags, but at that point you're probably better off writing a PHP script to do the job. It might not be quite as fast, but it will probably be faster to write.我正在传递这段代码,看起来与上面的非常相似。为我工作,希望有帮助。
I am passing this code on, seems very similar to the above. Worked for me, hope it helps.
与 MySQL 8+ 和 MariaDB 10.0.5+ 兼容
SELECT REGEXP_REPLACE(body, '<[^>]*>+', '') FROM app_cms_sections
Compatible with MySQL 8+ and MariaDB 10.0.5+
SELECT REGEXP_REPLACE(body, '<[^>]*>+', '') FROM app_cms_sections
我只是扩展了答案@boann 以允许定位任何特定标签,以便我们可以在每次函数调用时一一替换标签。您只需传递标签参数,例如
'a'
即可替换所有开始/结束锚标记。这回答了OP提出的问题,与接受的答案不同,后者删除了所有标签。I just extended the answer @boann to allow targetting of any specific tag so that we can replace out the tags one by one with each function call. You just need pass the tag parameter, e.g.
'a'
to replace out all opening/closing anchor tags. This answers the question asked by OP, unlike the accepted answer, which strips out ALL tags.一旦我添加了
SET $str = COALESCE($str, '');
,Boann 就可以工作了。来自此帖子:
Boann's works once I added
SET $str = COALESCE($str, '');
.from this post:
我正在使用 lib_mysqludf_preg 库和这样的正则表达式:
对于行也这样做带有编码的 html 实体:
在某些情况下,这些可能会失败,但我还没有遇到过,而且它们相当快。
I'm using the lib_mysqludf_preg library for this and a regex like this:
Also did it like this for rows which with encoded html entities:
There are probably cases where these might fail but I haven't encountered any and they're reasonably fast.
REPLACE()
效果很好。微妙的方法:
...以及不那么微妙的方法:(将字符串转换为段)
REPLACE()
works pretty well.The subtle approach:
...and the not so subtle: (Converting strings into slugs)