Maison > Article > développement back-end > PHP substr函数的实现功能技巧讲解_PHP教程
小弟不才整理了一下substr函数的用法,做了几个例子以解新人之惑,高手请飘过。
我们先来看一下PHP substr函数的语法:
string substr(string string, int start, int [length])
参数string为要操作的字符串
参数start为你要截取的字符串的开始位置,若start为负数时,则表示从倒数第start开始截取length个字符
可选参数length为你要截取的字符串长度,若在使用时不指定则默认取到字符串结尾。若length为负数时,则表示从start开始向右截取到末尾倒数第length个字符的位置
起初用这个函数时可能感觉到别扭,不过你要是把PHP substr函数的语法搞懂了,那他的功能比asp中的left和right,有过之无不及,非常好用。下面我们举例来看他的用法:
1、从第4个字符开始截取到字符串末尾,类似asp中的left:
<ol class="dp-xml"> <li class="alt"><span><span class="tag"><span> ?php </span></span></span></li> <li> <span>$</span><span class="attribute">str</span><span> = </span><span class="attribute-value">"www.designline.cn"</span><span>; </span> </li> <li class="alt"><span>echo substr($str,4); </span></li> <li> <span class="tag">?></span><span> </span> </li> </ol>
输出: designline.cn
2、PHP substr函数从右边截取3个字符,类似asp中的right:
<ol class="dp-xml"> <li class="alt"><span><span class="tag"><span class="tag-name">php</span><span> </span></span></span></li> <li> <span>$</span><span class="attribute">str</span><span> = </span><span class="attribute-value">"www.designline.cn"</span><span>; </span> </li> <li class="alt"><span>echo substr($str,-3); </span></li> <li> <span class="tag">?></span><span> </span> </li> </ol>
输出:.cn
3、PHP substr函数从第4个字符开始截取6个字符:
<ol class="dp-xml"> <li class="alt"><span><span class="tag"><span> ?php </span></span></span></li> <li> <span>$</span><span class="attribute">str</span><span> = </span><span class="attribute-value">"www.designline.cn"</span><span>; </span> </li> <li class="alt"><span>echo substr($str,4,6); </span></li> <li> <span class="tag">?></span><span> </span> </li> </ol>
输出:design
4、有时我们知道一个字符串的开始和结尾,中间是不定长的字符,这时除了用PHP substr函数的正则外我们还可以用substr实现(当然要得到中间的字符方法有N种,在此只是举例substr的应用):
<ol class="dp-xml"> <li class="alt"><span><span class="tag"><span> ?php </span></span></span></li> <li> <span>$</span><span class="attribute">str</span><span> = </span><span class="attribute-value">"www.designline.cn"</span><span>; </span> </li> <li class="alt"><span>echo substr($str,3,-3); </span></li> <li> <span class="tag">?></span><span> </span> </li> </ol>
输出:www.designline.cn