很多新手PHP学员在问PHP如何截取字符串,从左侧如何截取,从右侧又如何截取等等,今天青岛星网就带大家学习:PHP之substr函数截取字符串实例。
string substr(string string, int start, int [length])
参数string为要操作的字符串
参数start为你要截取的字符串的开始位置,若start为负数时,则表示从倒数第start开始截取length个字符
可选参数length为你要截取的字符串长度,若在使用时不指定则默认取到字符串结尾。若length为负数时,则表示从start开始向右截取到末尾倒数第length个字符的位置
1、从第4个字符开始截取到字符串末尾,类似asp中的left:
<?php $str = "www.qdxw.net"; echo substr($str,4); ?>
输出: qdxw.net
2、PHP substr函数从右边截取3个字符,类似asp中的right:
<?php $str = "www.qdxw.net"; echo substr($str,-3); ?>
输出:net
3、PHP substr函数从第4个字符开始截取3个字符:
<?php $str = "www.qdxw.net"; echo substr($str,4,3); ?>
输出:qdx
4、有时我们知道一个字符串的开始和结尾,中间是不定长的字符,这时除了用PHP substr函数的正则外我们还可以用substr实现(当然要得到中间的字符方法有N种,在此只是举例substr的应用):
本例去掉开头4个字符和结尾4个字符,输出中间的字符串:
<?php $str = "www.qdxw.net"; echo substr($str,4,-4); ?>
输出:qdxw
提高篇:php获取字符串中两个字符中间的字符
function getNeedBetween($kw1,$mark1,$mark2){ $b= (strpos($kw1,$mark1)); $c= (strpos($kw1,$mark2)); $d=strlen($mark1);$f=strlen($mark2); return substr($kw1,$b+$d,$c-$b-$d); }
扩展阅读:PHP截取字符串的函数使用方法 PHP汉字截取函数