How to extract substring by start-index and end-index?

后端 未结 5 1217
花落未央
花落未央 2021-02-02 06:12
$str = \'HelloWorld\';
$sub = substr($str, 3, 5);
echo $sub; // prints \"loWor\"

I know that substr() takes the first parameter, 2nd parameter is start

相关标签:
5条回答
  • 2021-02-02 06:35

    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);
    
    0 讨论(0)
  • 2021-02-02 06:41

    It's just math

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

    The length is the end minus the start.

    0 讨论(0)
  • 2021-02-02 06:46

    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:

    // 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.
    
    0 讨论(0)
  • 2021-02-02 06:57

    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).

    As stated at the substr documentation.

    0 讨论(0)
  • 2021-02-02 06:59
    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:

    function my_substr_function($str, $start, $end)
    {
      return mb_substr($str, $start, $end - $start);
    }
    
    0 讨论(0)
提交回复
热议问题