Home > Database > Mysql Tutorial > body text

How to use replace function in mysql

下次还敢
Release: 2024-04-29 04:09:15
Original
1063 people have browsed it

The REPLACE() function in MySQL is used to replace characters or substrings in a string. Its syntax is: REPLACE(string, search_string, replace_string). It supports replacing multiple substrings simultaneously, using regular expressions for replacement, and replacing null values. For example, the following example replaces "Apple" with "Banana" in the string: SELECT REPLACE('I love Apple', 'Apple', 'Banana');

How to use replace function in mysql

Usage of REPLACE() function in MySQL

The REPLACE() function is used to replace characters or substrings in a string. The syntax is as follows:

<code class="sql">REPLACE(string, search_string, replace_string)</code>
Copy after login

Parameter description:

  • string: The string that needs to replace characters.
  • search_string: The substring to be replaced.
  • replace_string: New substring used to replace search_string.

Usage example:

The following example replaces "Apple" in the string with "Banana":

<code class="sql">SELECT REPLACE('I love Apple', 'Apple', 'Banana');</code>
Copy after login

Output:

<code>I love Banana</code>
Copy after login

Other usage:

1. Replace multiple substrings

The REPLACE() function can replace multiple subcharacters at the same time string. For example, the following statement replaces "a" and "e" with "o" in the string:

<code class="sql">SELECT REPLACE('apple', 'a', 'o')
SELECT REPLACE('apple', 'e', 'o')</code>
Copy after login

Output:

<code>opple
oploe</code>
Copy after login

2. Use regular expressions

The REPLACE() function supports replacement using regular expressions. For example, the following statement replaces all numbers in the string with "*":

<code class="sql">SELECT REPLACE('12345', '[0-9]', '*')</code>
Copy after login

Output:

<code>*****</code>
Copy after login

3. Replace empty values

REPLACE () function can be used to replace null values. For example, the following statement replaces null values ​​in a string with "N/A":

<code class="sql">SELECT REPLACE(NULL, NULL, 'N/A')</code>
Copy after login

Output:

<code>N/A</code>
Copy after login

The above is the detailed content of How to use replace function in mysql. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template