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

后端 未结 5 1222
花落未央
花落未央 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: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.
    

提交回复
热议问题