概述
在PHP
的实战中,我们经常需要对URL
字符串进行解析,截取我们所需要的片段,PHP
为我们提供了substr()
函数,我们可很轻松的获取我们所需要的数据,本文就带大家一起来看一看PHP
中的substr()
函数。
首先我们先看一看看substr()
函数的语法:
substr ( string $string , int $start , int $length = ? )
登录后复制
$string:需要截取的原字符串
$start:需要开始的索引位置(值可以为正整数、负整数、0)
$length:需要筛选的长度(值可以为正整数、负整数、0)若为空则默认截取至结束
返回值:经过截取得到的新字符串,若错误则返回false。
代码实例:
1.若参数都为非负整数
<?php
echo substr('uoften.com is all right', 1);
echo "<br>";
echo substr('uoften.com is all right', 1, 3);
echo "<br>";
echo substr('uoften.com is all right', 0, 4);
echo "<br>";
echo substr('uoften.com is all right', 0, 8);
?>
登录后复制
输出: hp.cn is all right
hp.
php.
uoften.com i
登录后复制
2.若$start出现负整数
<?php
echo substr("uoften.com is all right", -1);
echo "<br>";
echo substr("uoften.com is all right", -2);
echo "<br>";
echo substr("uoften.com is all right", -3, 1);
?>
登录后复制
输出:
t
ht
g
登录后复制
3.若$length出现负整数
<?php
echo substr("uoften.com is all right", 0,-1);
echo "<br>";
echo substr("uoften.com is all right",2, -1);
echo "<br>";
echo substr("uoften.com is all right",4, 4);
echo "<br>";
echo substr("uoften.com is all right",-3, -1);
?>
登录后复制
输出:uoften.com is all righ
p.cn is all righ
cn i
gh
登录后复制
推荐:《2021年PHP面试题大汇总(收藏)》《php视频教程》
以上就是PHP中substr()函数的解析(附代码详解)的详细内容,更多请关注靠谱客其它相关文章!
最后
以上就是高兴海燕为你收集整理的PHP中substr()函数的解析(附代码详解)的全部内容,希望文章能够帮你解决PHP中substr()函数的解析(附代码详解)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复