To perform a search/replace on only the first occurrence, use the CONCAT and REPLACE() functions.
Query as follows to set user-defined session variables -
mysql> set @Sentence='Thks ks is a my string'; Query OK, 0 rows affected (0.00 sec)
Here, k will be replaced by i only once. The query is as follows. We also used INSTR() -
mysql> select @Sentence as NewString ,CONCAT(REPLACE(LEFT(@Sentence, INSTR(@Sentence, 'k')), 'k', 'i'), -> SUBSTRING(@Sentence, INSTR(@Sentence, 'k') + 1)) as ChangeOnlyOneTime;
The following is the output showing only the first occurrence of the character being replaced -
+------------------------+------------------------+ | NewString | ChangeOnlyOneTime | +------------------------+------------------------+ | Thks ks is a my string | This ks is a my string | +------------------------+------------------------+ 1 row in set (0.00 sec)
The above is the detailed content of Perform a search/replace on only the first occurrence of a session variable in MySQL. For more information, please follow other related articles on the PHP Chinese website!