3

I try to create a MySQL function to parse a given string into a version I can use in an URL. So I have to eliminate some special characters and I try to do it with a loop to keep the code simple and to not have to specify any character.

My current code is:

DECLARE parsedString VARCHAR(255);

# convert to low chars
SET parsedString    =   CONVERT(paramString USING latin1);
SET parsedString    =   LOWER(parsedString);

# replace chars with A
SET @x = 223;

charReplaceA: WHILE @x <= 229 DO
    SET @x = @x + 1;

    SET parsedString    =   REPLACE (parsedString, CHAR(@x USING ASCII), 'a');
END WHILE charReplaceA;

# convert to utf8 and return
RETURN CONVERT(parsedString USING utf8);

If I try to use my code it doesn't work. Somehow it doesn't recognize the CHAR(@x USING ASCII) part.

SELECT urlParser('aäeucn');

returns

aäeucn

If I change my code to

SET parsedString    =   REPLACE (parsedString, 'ä', 'a');

it somehow works and returns

aaeucn

Does anyone have any idea how to use REPLACE() with CHAR()? I don't want to specify any possible character.

4

1 回答 1

1

你可以试试

REPLACE(CONVERT('aäeucn' USING ascii), '?', 'a')

将国际字符转换为 ascii 时,所有非 ascii 字符均由文字“?”表示 特点。然后您不必执行循环(因此它可能会运行得更快)。

还要考虑在 URL 中编码国际字符的其他方法。
http://www.w3.org/International/articles/idn-and-iri/


回复您的评论:

如果您需要逐个字符替换,我不会在 SQL 函数中执行此操作。MySQL 函数效率不高,编码和调试很麻烦。我建议将 utf8 字符串取回您的应用程序并在那里进行字符翻译。

您没有指定您正在使用哪种应用程序编程语言,但就其价值而言,PHP 支持strtr()可用于此场景的函数。手册页中甚至还有一个将 i18n 字符映射到 ascii 字符的示例:http: //php.net/strtr

$addr = strtr($addr, "äåö", "aao"); // That was easy!

该解决方案将比 MySQL 存储函数更快、更容易编写代码。

于 2012-12-26T17:27:14.707 回答