2016-05-28 51 views
1

作为将网站迁移到HTTPS的一部分,我将博客文章中的HTTP URL更改为相对URL。只更新列的一部分 - 多行

当前数据articles表:

╔════╦═══════════════════════════════════════════════════════════════╗ 
║ ID ║ content              ║ 
╠════╬═══════════════════════════════════════════════════════════════╣ 
║ 1 ║ lorem ipsum <a href='http://www.example.com/'>link</a> etc ║ 
║ 2 ║ see more <a href='http://www.example.com/page.html'>here</a> ║ 
║ 3 ║ bla bla bla <img src='http://www.example.com/image.jpg' /> ║ 
╚════╩═══════════════════════════════════════════════════════════════╝ 

所需的输出与相对URL:

╔════╦═══════════════════════════════════════════════════════════════╗ 
║ ID ║ content              ║ 
╠════╬═══════════════════════════════════════════════════════════════╣ 
║ 1 ║ lorem ipsum <a href='//www.example.com/'>link</a> etc   ║ 
║ 2 ║ see more <a href='//www.example.com/page.html'>here</a>  ║ 
║ 3 ║ bla bla bla <img src='//www.example.com/image.jpg' />   ║ 
╚════╩═══════════════════════════════════════════════════════════════╝ 

注:这些硬编码

  • 有几百行链接。
  • 每行可以包含更多链接。

我想今天过的每一行,改变与正则表达式中的链接,然后更新该行。

$query = $db->query("SELECT id,content FROM articles WHERE content LIKE '%http://www.example.com%'"); 
while ($row = $query->fetch_row()) { 
    $updatedContent = /* some regex to remove the "http:" part */ 
    $db->query("UPDATE articles SET content = ..."); 
} 

但因为我想学习新的东西,我的问题是:

是否有其他办法吗?可能有一些正则表达式在PostgreSQL,将允许只更新列的一部分,而不是浪费资源在数百行上,每个行都有数千个字符?

回答

2

你不需要PHP。它可以通过一个简单的数据库查询来完成:

UPDATE articles SET content = REPLACE(content, 'http:', '');

+2

你也可以用WHERE过滤: 'UPDATE your_table SET your_field = REPLACE(your_field, 'HTTP:', '') WHERE your_field LIKE '%HTTP%'' –