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 红包祝福语简短10字
18 周六早晨祝福语简短