MySQL字符串截取函数
虽然在实际应用中使用程序来处理字符串截取类的操作会比使用数据库函数来实现截取的效率更好一些,但多掌握一些 MySQL 函数还是非常有必要的。这里介绍几个 MySQL 字符串截取函数,分别有:left(), right(), substring(), substring_index()。还有 mid(), substr()等。其中,mid(), substr() 等价于 substring() 函数,substring() 是一个非常强大的函数的。下面以示例分别说明每个函数的用法。
(1)left(str,length)
mysql> select left('www.phpernote.com',3);
+------------------------------+
| left('www.phpernote.com', 3) |
+------------------------------+
| www |
+------------------------------+
(2)right(str,length)
mysql> select right('www.phpernote.com',3);
+-------------------------------+
| right('www.phpernote.com', 3) |
+-------------------------------+
| com |
+-------------------------------+
(3)substring(str, pos)
mysql> select substring('www.phpernote.com', 5);
+-----------------------------------+
| substring('www.phpernote.com', 5) |
+-----------------------------------+
| phpernote.com |
+-----------------------------------+
mysql> select substring('www.phpernote.com', -4);//从字符串的第 4 个字符位置(倒数)开始取,直到结束
+------------------------------------+
| substring('www.phpernote.com', -4) |
+------------------------------------+
| .com |
+------------------------------------+
(4)substring(str, pos, len)//注意此处参数pos可取负值,但len必须是正值
mysql> select substring('www.phpernote.com', 5, 3);
+--------------------------------------+
| substring('www.phpernote.com', 5, 3) |
+--------------------------------------+
| php |
+--------------------------------------+
mysql> select substring('www.phpernote.com', -4, 3);//从字符串的第 4 个字符位置(倒数)开始取,只取 3 个字符
+---------------------------------------+
| substring('www.phpernote.com', -4, 3) |
+---------------------------------------+
| .co |
+---------------------------------------+
(5)substring_index(str,delim,count)
mysql> select substring_index('www.phpernote.com', '.', 2);//截取第二个 '.' 之前的所有字符
+------------------------------------------------+
| substring_index('www.phpernote.com', '.', 2) |
+------------------------------------------------+
| www.phpernote |
+------------------------------------------------+
mysql> select substring_index('www.phpernote.com', '.', -2);//截取倒数第二个 '.' 之后的所有字符
+-------------------------------------------------+
| substring_index('www.phpernote.com', '.', -2) |
+-------------------------------------------------+
| com |
+-------------------------------------------------+
mysql> select substring_index('www.phpernote.com', '.coc', 1);//如果在字符串中找不到 delim 参数指定的值,就返回整个字符串
+---------------------------------------------------+
| substring_index('www.phpernote.com', '.coc', 1) |
+---------------------------------------------------+
| www.phpernote.com |
+---------------------------------------------------+
您可能感兴趣的文章
- php最精确的字符串长度截取函数
- MySQL replace函数替换字符串语句的用法
- Mysql查询带单引号字符串及插入带单引号字符串需要注意问题
- javascript的字符串编码函数escape,encodeURI,encodeURIComponent比较与分析
- javascript实现截取字符串功能总结(包括使用Js截取中文字符的介绍)
- mysql批量清除字符串空格的方法
- php字符串替换函数str_replace速度比preg_replace快
- php被遗忘的一些功能强大的字符串处理函数