Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 views
in Technique[技术] by (71.8m points)

encoding - mysql substitute html special chars with UTF equivalents

I have a database where some of the elements consist of HTML special characters:

| Universidad Tecnológica Nacional - UTN                                                  |
| Instituto Tecnológico de Buenos Aires                                                   |
| Instituto Superior del Profesorado "Dr. Joaquín V. González" |
| Escuela Nacional de Náutica "Manuel Belgrano"                         |
| Conservatorio Nacional de Música "Carlos López Buchardo"     |
| Instituto Argentino de Computacion - IAC                                                         |
| Conservatorio de Superior de Música "Manuel de Falla"                 |

I need to convert it to a proper UTF format. Can I do better than just iterating through the database, and having a mapping from each code to the equivalent symbol?

á -> 'á'
" -> '"'
...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As mentioned in my comment above, it's terribly unclear what you're trying to do in your own case.

Can I do better than just iterating through the database, and having a mapping from each code to the equivalent symbol?

Well, yes. You can replace character code entities (e.g. { and ƫ) with their replacement characters without having to lookup the character code in a "mapping". But named entities (e.g. ") will always need to be looked up.

Here's my attempt to solve the general case:

  1. Create a table to store named character entities defined in HTML:

    CREATE TABLE ents (
      ref VARCHAR(8) NOT NULL COLLATE utf8_bin,
      rep CHAR(1)    NOT NULL,
      PRIMARY KEY (ref)
    );
    
  2. Populate this table - I suggest using a script, for example from PHP:

    $dbh = new PDO("mysql:dbname=$dbname", $username, $password);
    $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
    $ins = $dbh->prepare('INSERT INTO ents (ref, rep) VALUES (?, ?)');
    $t = get_html_translation_table(HTML_ENTITIES);
    foreach ($t as $k => $v) $ins->execute([substr($v, 1, -1), $k]);
    
  3. Define an SQL function to perform entity replacements (using this table where applicable, or else by character code):

    DELIMITER ;;
    
    CREATE FUNCTION dhe(s TEXT) RETURNS TEXT
    BEGIN
      DECLARE n, p, i, t INT DEFAULT 0;
      DECLARE r VARCHAR(12);
      entity_search: LOOP
        SET n := LOCATE('&', s, n+1);
        IF (!n) THEN
          LEAVE entity_search;
        END IF;
    
        IF (SUBSTRING(s, n+1, 1) = '#') THEN
          CASE
            WHEN SUBSTRING(s, n+2, 1) RLIKE '[[:digit:]]' THEN
              SET t := 2, p := n+2, r := '[[:digit:]]';
            WHEN SUBSTRING(s, n+2, 1) = 'x' THEN
              SET t := 3, p := n+3, r := '[[:xdigit:]]';
            ELSE ITERATE entity_search;
          END CASE;
        ELSE
          SET t := 1, p := n+1, r := '[[:alnum:]_]';
        END IF;
    
        SET i := 0;
        reference: LOOP
          IF SUBSTRING(s, p+i, 1) NOT RLIKE r THEN
            IF SUBSTRING(s, p+i, 1) RLIKE '[[:alnum:]_]' THEN
              ITERATE entity_search;
            END IF;
            LEAVE reference;
          END IF;
          IF i = 8 THEN ITERATE entity_search; END IF;
          SET i := i + 1;
        END LOOP reference;
    
        SET s := CONCAT(
          LEFT(s, n-1),
          CASE t
            WHEN 1 THEN COALESCE(
              (SELECT rep FROM ents WHERE ref = SUBSTRING(s, p, i))
            , SUBSTRING(s, n, i + IF(SUBSTRING(s, p+i, 1)=';',1,0))
            )
            WHEN 2 THEN CHAR(SUBSTRING(s, p, i))
            WHEN 3 THEN CHAR(CONV(SUBSTRING(s, p, i), 16, 10))
          END,
          SUBSTRING(s, p + i + IF(SUBSTRING(s, p+i, 1)=';',1,0))
        );
      END LOOP entity_search;
      RETURN s;
    END;;
    
    DELIMITER ;
    
  4. Apply this function twice to decode your (apparently) doubly-encoded table:

    UPDATE my_table SET my_column = dhe(dhe(my_column));
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...