substr()
方法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