代码之家  ›  专栏  ›  技术社区  ›  Alexis Vandepitte

如何在mysql数据库中用换行符搜索和替换空html表行

  •  2
  • Alexis Vandepitte  · 技术社区  · 7 年前

    我需要在mysql数据库中搜索并替换此html(通过phpMyAdmin):

    <tr>
    <td></td>
    <td></td>
    </tr>
    

    但我不知道怎么找到它,因为它有断线。

    我目前的查询是:

    UPDATE `wp_posts`
     SET `post_content` = replace(post_content, '<tr>
                                  <td></td>
                                  <td></td>
                                  </tr>', '')
    

    我如何瞄准它?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Derviş Kayımbaşıoğlu    7 年前

    你可以用 REGEXP_REPLACE

    REGEXP_REPLACE(x, '<tr>(\s*\r*\n*\s*<td>\s*\r*\n*\s*</td>){2}\s*\r*\n*\s*</tr>', '<<replaced>>' )
    
    • \n 是linux风格的新线吗
    • \r\n 是windows风格的新线吗
    • \s 是空格字符吗

    create table t (x varchar(1000));
    
    ✓
    
    insert into t values ('before <tr>\n<td></td>\n<td></td>\n</tr> after')
    
    
      
    select * from t
    
    | x                                                    |
    | :--------------------------------------------------- |
    | before <tr><br><td></td><br><td></td><br></tr> after |
    
    select REGEXP_REPLACE(x, '<tr>(\s*\r*\n*\s*<td>\s*\r*\n*\s*</td>){2}\s*\r*\n*\s*</tr>', '<<replaced>>' ) from t
    
    | REGEXP_REPLACE(x, '<tr>(\s*\r*\n*\s*<td>\s*\r*\n*\s*</td>){2}\s*\r*\n*\s*</tr>', '<<replaced>>' ) |
    | :------------------------------------------------------------------------------------------------ |
    | before <<replaced>> after                                                                         |
    
    update t set x = REGEXP_REPLACE(x, '<tr>(\s*\r*\n*\s*<td>\s*\r*\n*\s*</td>){2}\s*\r*\n*\s*</tr>', '<<replaced>>' )
    
    ✓
    

    db<&燃气轮机;不停摆弄 here

        2
  •  0
  •   GMB    7 年前

    如果你想更换 由四行组成的线 ,你需要注意的一件事是换行。例如,在查询中,第2、3和4行的开头有额外的空格,这些空格可能不匹配。

    根据您的设置,可能会出现换行 \r\n \n .

    UPDATE `wp_posts` 
    SET `post_content` = REPLACE(
        post_content, 
        '<tr>\n<td></td>\n<td></td>\n</tr>', 
        ''
      )
    

    如果你想更换 4个不同的字符串 ,然后您可以逐个运行更新,或者生成4级deedp嵌套 REPLACE()

    UPDATE `wp_posts` SET `post_content` = REPLACE(post_content, '<tr>', '');
    UPDATE `wp_posts` SET `post_content` = REPLACE(post_content, '<td></td>', '');
    

    UPDATE `wp_posts` 
    SET `post_content` = 
        REPLACE(
            REPLACE(
                 post_content, 
                '<td></td>',
                ''
            ),
            '<tr>', 
            ''
        )
    ;