Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/249.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何通过开始索引和结束索引提取子字符串?_Php - Fatal编程技术网

Php 如何通过开始索引和结束索引提取子字符串?

Php 如何通过开始索引和结束索引提取子字符串?,php,Php,我知道substr()接受第一个参数,第二个参数是start index,而第三个参数是要提取的子字符串长度。我需要的是通过startIndex和endIndex提取子字符串。我需要的是这样的东西: $str = 'HelloWorld'; $sub = substr($str, 3, 5); echo $sub; // prints "loWor" 在php中有这样做的函数吗?或者你能帮我找到一个解决办法吗?这只是数学问题 $str = 'HelloWorld'; $sub = my_sub

我知道substr()接受第一个参数,第二个参数是start index,而第三个参数是要提取的子字符串长度。我需要的是通过startIndexendIndex提取子字符串。我需要的是这样的东西:

$str = 'HelloWorld';
$sub = substr($str, 3, 5);
echo $sub; // prints "loWor"
在php中有这样做的函数吗?或者你能帮我找到一个解决办法吗?

这只是数学问题

$str = 'HelloWorld';
$sub = my_substr_function($str, 3, 5);
echo $sub; // prints "lo"

长度是结束减去开始。

只要从结束索引中减去开始索引,就得到了函数想要的长度

$sub = substr($str, 3, 5 - 3);
如果需要多字节安全(即,对于汉字,…),请使用mb_substr函数:

function my_substr_function($str, $start, $end)
{
  return substr($str, $start, $end - $start);
}
不完全是

如果我们的起始索引为0,并且我们只需要第一个字符,这将变得很困难,因为这将无法输出您想要的内容。因此,如果您的代码需要$end_索引:

function my_substr_function($str, $start, $end)
{
  return mb_substr($str, $start, $end - $start);
}

您可以在第三个参数上使用负值:

// 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.
如果给定的长度为负数,那么许多字符将从字符串末尾被省略(当开始为负数时,在计算开始位置之后)


正如在.

上所述,虽然“变通解决方案”很简单,但这实际上是一个好问题,因为大多数编程语言都有两个版本的子字符串提取函数(通常称为“substr”和“substring”),一个是长度参数,另一个是结束索引参数。看起来PHP不是这样的,我希望PHP能像Javascript的子字符串一样有这样的功能。像这样的小事情让我恼火。@eviriko,现在你可以看到substr()如何变得更加复杂。如果我只需要第一个字符,我将使用
substr($str,0,1-0)我没有看到任何棘手或复杂的事情我所指的“棘手”部分是,如果您的结束索引为0或小于开始索引,您将得到意外的结果。摆脱这个问题的一个方法是通过上面提到的答案。您的评论“如果我只想要第一个…”告诉我您完全控制着开始和结束索引变量。但是,如果将此控件赋予程序,则可以有一个开始变量和结束变量,例如
$start\u index=0$结束指数=0
$start\u index=0$终点指数=-10。您必须小心控制这些$variables的是什么。因此,我认为这比公认的答案更一般、更好。内部substr(…)不应该是mb_substr(…)-以防万一…?嗯,我们大多数人可能不处理多字节字符。。。但是,是的,这是有意义的,也是有效的评论(我用你的建议扩展了我的答案)。谢谢,+1!i、 e.没有内置的PHP函数来执行此操作;您应该使用
substr()
// 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.
echo substr('HelloWorld', 3, -5);
// will print "lo"