$str = 'HelloWorld';
$sub = substr($str, 3, 5);
echo $sub; // prints "loWor"
Run Code Online (Sandbox Code Playgroud)
我知道substr()接受第一个参数,第二个参数是起始索引,而第三个参数是要提取的子串长度.我需要的是通过startIndex和endIndex提取子字符串.我需要的是这样的:
$str = 'HelloWorld';
$sub = my_substr_function($str, 3, 5);
echo $sub; // prints "lo"
Run Code Online (Sandbox Code Playgroud)
是否有一个函数在PHP中执行此操作?或者,您能帮我解决一下解决方案吗?
Kin*_*nch 76
这只是数学
$sub = substr($str, 3, 5 - 3);
Run Code Online (Sandbox Code Playgroud)
长度是结束减去开始.
And*_*eas 16
function my_substr_function($str, $start, $end)
{
return substr($str, $start, $end - $start);
}
Run Code Online (Sandbox Code Playgroud)
如果你需要多字节安全(即中文字符,...)使用mb_substr函数:
function my_substr_function($str, $start, $end)
{
return mb_substr($str, $start, $end - $start);
}
Run Code Online (Sandbox Code Playgroud)
只需从结束索引中减去起始索引,就可以得到函数所需的长度.
$start_index = 3;
$end_index = 5;
$sub = substr($str, $start_index, $end_index - $start_index);
Run Code Online (Sandbox Code Playgroud)
您可以只对第三个参数使用负值:
echo substr('HelloWorld', 3, -5);
// will print "lo"
Run Code Online (Sandbox Code Playgroud)
如果给定 length 并且为负数,那么从字符串的末尾将省略许多字符(在开始为负数时计算开始位置之后)。