PHP substr()函数与示例
PHPsubstr()方法
substr()函数是PHP中的字符串函数,用于从字符串的指定索引中获取子字符串。
语法:
substr(string, start, [length]);
这里,
字符串是主字符串。
start是字符串的起始索引,子字符串从该索引处返回。
length是一个可选参数,它定义要返回的字符数。
注意:负值指向字符串的末尾。例如:-1指向最后一个字符,-2指向倒数第二个字符,-3指向倒数第三个字符,依此类推...
例子:
Input:
str = "Hello friends how are your friends?";
start =10
Output:
"nds how are your friends?"
str = "Hello friends how are your friends?";
start =10
length = 5
Output:
"nds h"PHP代码:
<?php $str = "Hello friends how are your friends?"; //将子字符串从第10个索引返回到字符串的末尾 $substring = substr($str,10); echo ($substring . "\n"); //将子串从第10个索引返回到下一个5个字符 $substring = substr($str,10,5); echo ($substring . "\n"); //使用负值进行测试 $substring = substr($str,-1); echo ($substring . "\n"); //使用负值进行测试 $substring = substr($str,10,-1); echo ($substring . "\n"); //使用负值进行测试 $substring = substr($str,-5); echo ($substring . "\n"); //使用负值进行测试 $substring = substr($str,3,-5); echo ($substring . "\n"); ?>
输出结果
nds how are your friends? nds h ? nds how are your friends ends? lo friends how are your fri
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短