Home >Database >Mysql Tutorial >How to remove all non-alphanumeric characters from a string in MySQL?

How to remove all non-alphanumeric characters from a string in MySQL?

PHPz
PHPzforward
2023-08-29 15:41:02738browse

如何从 MySQL 中的字符串中删除所有非字母数字字符?

Non-alphanumeric characters are as follows -

@,!,#,&,(),?, /

There is no built-in function in MySQL to remove non-alphanumeric characters from a string. Therefore, we create a function that removes all non-alphanumeric characters. The function declaration and definition are as follows.

mysql> delimiter //
mysql> CREATE FUNCTION RemoveNonAlphaNumeric( s CHAR(255) ) RETURNS CHAR(255) DETERMINISTIC
   -> BEGIN
   ->   DECLARE var1, length SMALLINT DEFAULT 1;
   ->   DECLARE result CHAR(255) DEFAULT '';
   ->   DECLARE ch CHAR(1);
   ->   SET length  = CHAR_LENGTH( s );
   ->   REPEAT
   ->     BEGIN
   ->       SET ch = MID( s, var1, 1 );
   ->       IF ch REGEXP '[[:alnum:]]' THEN
   ->         SET result =CONCAT(result ,ch);
   ->       END IF;
   ->       SET var1 = var1 + 1;
   ->     END;
   ->   UNTIL var1 >length  END REPEAT;
   ->   RETURN result ;
   -> END //
Query OK, 0 rows affected (0.10 sec)

The function named "RemoveNonAlphaNumeric" removes all non-alphanumeric characters from a string. To check, we will now call the user-defined function.

mysql>delimiter ;
mysql>  select 'My Email id is test@123!',RemoveNonAlphaNumeric('My Email id is test@123!');

The following is the output showing the successful removal of alphanumeric characters using the function "RemoveNonAlphaNumeric".

+--------------------------+---------------------------------------------------+
| My Email id is test@123! | removeNonAlphaNumeric('My Email id is test@123!') |
+--------------------------+---------------------------------------------------+
| My Email id is test@123! | MyEmailidistest123                                |
+--------------------------+---------------------------------------------------+
1 row in set (0.15 sec)

In this string (MyEmailidistest123), there are no @ and! There are now symbols, which means the function is working fine.

The above is the detailed content of How to remove all non-alphanumeric characters from a string in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete