【问题标题】:How to extract substring by start-index and end-index?如何通过开始索引和结束索引提取子字符串?
【发布时间】:2011-08-11 21:35:11
【问题描述】:
$str = 'HelloWorld';
$sub = substr($str, 3, 5);
echo $sub; // prints "loWor"

我知道 substr() 采用第一个参数,第二个参数是起始索引,而第三个参数是要提取的子串长度。我需要的是通过 startIndexendIndex 提取子字符串。我需要的是这样的:

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

在 php 中是否有一个函数可以做到这一点?或者你能帮我解决一个解决办法吗?

【问题讨论】:

  • 虽然“变通解决方案”很简单,但这实际上是一个好问题,因为大多数编程语言确实有两个版本的子字符串提取函数(通常可怕地命名为“substr”和“substring”)一个带有长度参数,另一个带有 end-index 参数。看来PHP不是这样的。
  • 我希望 PHP 有这个,就像 Javascript 的子字符串一样。就是这样的小事让我很恼火。

标签: php


【解决方案1】:

这只是数学

$sub = substr($str, 3, 5 - 3);

长度是结束减去开始。

【讨论】:

  • 即没有内置的 PHP 函数可以这样做;你应该使用substr()
【解决方案2】:
function my_substr_function($str, $start, $end)
{
  return substr($str, $start, $end - $start);
}

如果您需要多字节安全(即对于中文字符,...),请使用 mb_substr 函数:

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

【讨论】:

  • 我认为它比接受的答案更笼统,更好。
  • 内部 substr(...) 不应该是 mb_substr(...) - 以防万一吗?
  • 好吧,我们大多数人可能不处理多字节字符......但是,它确实有意义并且是有效的评论(我根据您的建议扩展了我的答案)。谢谢,+1!
【解决方案3】:

只需从结束索引中减去开始索引,即可得到函数所需的长度。

$start_index = 3;
$end_index = 5;
$sub = substr($str, $start_index, $end_index - $start_index);

【讨论】:

    【解决方案4】:

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

    echo substr('HelloWorld', 3, -5);
    // will print "lo"
    

    如果给定长度并且是负数,那么从字符串的末尾会省略很多字符(当开始为负数时计算开始位置之后)。

    substr documentation 所述。

    【讨论】:

      【解决方案5】:

      不完全是……

      如果我们的起始索引为 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.
      

      【讨论】:

      • @evilReiko,现在你可以看到 substr() 是多么的棘手。
      • 如果我只想要第一个字符,我会使用substr($str, 0, 1 - 0); 我没有看到任何棘手或复杂的内容
      • 我所指的“棘手”部分是,如果您的结束索引小于或等于起始索引,则会得到意想不到的结果。摆脱这个问题的一种方法是通过上述答案。你的评论,'如果我只想要第一个......'告诉我你完全控制了开始和结束索引变量。但是,如果将此控制权交给程序,则可以有一个开始变量和结束变量,例如$start_index = 0; $end_index = 0;$start_index = 0; $end_index = -10;。您必须小心控制这些 $variables 的内容。因此,技巧
      猜你喜欢
      • 2021-04-19
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 2013-09-10
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 2013-06-16
      相关资源
      最近更新 更多