SQL query to replace string based on wildcardt

前端 未结 1 1179
故里飘歌
故里飘歌 2021-01-24 00:59

I would like to run this type of query on my WP database to remove all span instances with id=\"more-\":

UPDATE wp_posts SET post_content = REPLACE (
post_conte         


        
相关标签:
1条回答
  • 2021-01-24 01:19

    In MySQL version 8.0 and above, you can use REGEX_REPLACE() function. In absence of the same, some complicated string operations can be done. This is based on your confirmation, that the said sub-string is occurring only once in a value.

    REPLACE() does not have any support for wildcards, patterns, regular expressions etc. It only replaces a given fixed substring with another fixed substring, in a bigger string.

    Instead, we can try to extract portions of the post_content. We will extract the leading substring before the '<p><span id="more-' using Substring_Index() function. Similarly, we will extract the trailing substring after the '"></span></p>' portion.

    Now, we can simply Concat() these portions to get the required post_content. You can find details of various String functions used here: https://dev.mysql.com/doc/refman/8.0/en/string-functions.html

    I have also added a WHERE condition, so that we pick only those rows which match our given substring criteria.

    UPDATE wp_posts 
    SET post_content = 
    CONCAT( 
           SUBSTRING_INDEX(post_content, 
                           '<p><span id="more-', 
                           1), 
           SUBSTRING(post_content, 
                     LOCATE('"></span></p>', 
                            post_content, 
                            LOCATE('<p><span id="more-',
                                   post_content)
                            ) + 13) -- 13 is character length of "></span></p>
          )
    WHERE post_content LIKE '%<p><span id="more-%"></span></p>%';
    

    Query #1: Data before Update operations

    SELECT * FROM wp_posts;
    
    | post_content                                            |
    | ------------------------------------------------------- |
    | adasdaadsa<p><span id="more-35075"></span></p>121324124 |
    | 1412123123<p><span id="more-232"></span></p>adasdaafas  |
    

    Query #2: Data after Update operations

    SELECT * FROM wp_posts;
    
    | post_content         |
    | -------------------- |
    | adasdaadsa121324124  |
    | 1412123123adasdaafas |
    

    View on DB Fiddle

    0 讨论(0)
提交回复
热议问题