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
Release: 2023-08-29 15:41:02
forward
736 people have browsed it

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

Non-alphanumeric characters are as follows -

@,!,#,&,(),?, /
Copy after login

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)
Copy after login

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!');
Copy after login

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)
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template