php 如何通过开始索引和结束索引提取子串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7033167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to extract substring by start-index and end-index?
提问by evilReiko
$str = 'HelloWorld';
$sub = substr($str, 3, 5);
echo $sub; // prints "loWor"
I know that substr() takes the first parameter, 2nd parameter is start index, while 3rd parameter is substring length to extract. What I need is to extract substring by startIndexand endIndex. What I need is something like this:
我知道 substr() 需要第一个参数,第二个参数是起始索引,而第三个参数是要提取的子串长度。我需要的是通过startIndex和endIndex提取子字符串。我需要的是这样的:
$str = 'HelloWorld';
$sub = my_substr_function($str, 3, 5);
echo $sub; // prints "lo"
Is there a function that does that in php? Or can you help me with a workaround solution, please?
在 php 中有一个函数可以做到这一点吗?或者你能帮我解决一个解决方法吗?
回答by KingCrunch
It's just math
这只是数学
$sub = substr($str, 3, 5 - 3);
The length is the end minus the start.
长度是结束减去开始。
回答by Andreas
function my_substr_function($str, $start, $end)
{
return substr($str, $start, $end - $start);
}
If you need to have it multibyte safe (i.e. for chinese characters, ...) use the mb_substr function:
如果您需要多字节安全(即对于中文字符,...),请使用 mb_substr 函数:
function my_substr_function($str, $start, $end)
{
return mb_substr($str, $start, $end - $start);
}
回答by Dan Grossman
Just subtract the start index from the end index and you have the length the function wants.
只需从结束索引中减去开始索引,即可获得函数所需的长度。
$start_index = 3;
$end_index = 5;
$sub = substr($str, $start_index, $end_index - $start_index);
回答by Tim
You can just use a negative value on the third parameter:
您可以只对第三个参数使用负值:
echo substr('HelloWorld', 3, -5);
// will print "lo"
If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative).
如果给定 length 并且为负数,那么从字符串的末尾将省略许多字符(在开始为负数时计算开始位置之后)。
As stated at the substr documentation.
回答by BlackBeltScripting
Not exactly...
不完全是...
If we have a start index as 0, and we want JUST the first char, it becomes difficult as this will not output what you want. So if your code is requiring an $end_index:
如果我们的起始索引为 0,并且我们只想要第一个字符,这将变得很困难,因为这不会输出您想要的内容。因此,如果您的代码需要 $end_index:
// We want just the first char only.
$start_index = 0;
$end_index = 0;
echo $str[$end_index - $start_index]; // One way... or...
if($end_index == 0) ++$end_index;
$sub = substr($str, $start_index, $end_index - $start_index);
echo $sub; // The other way.