Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

$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 startIndex and endIndex. What I need is something like this:

$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?

like image 373
evilReiko Avatar asked Aug 11 '11 21:08

evilReiko


People also ask

How do substring () and substr () differ?

The difference between substring() and substr()The two parameters of substr() are start and length , while for substring() , they are start and end . substr() 's start index will wrap to the end of the string if it is negative, while substring() will clamp it to 0 .

How can you extract a substring from a given string?

You can extract a substring from a string before a specific character using the rpartition() method. rpartition() method partitions the given string based on the last occurrence of the delimiter and it generates tuples that contain three elements where.

How do you find the substring at the end of a string?

To extract a substring that begins at a specified character position and ends before the end of the string, call the Substring(Int32, Int32) method. This method does not modify the value of the current instance. Instead, it returns a new string that begins at the startIndex position in the current string.

How do you get a Subtring?

The substring() method extracts characters, between two indices (positions), from a string, and returns the substring. The substring() method extracts characters from start to end (exclusive). The substring() method does not change the original string.


2 Answers

It's just math

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

The length is the end minus the start.

like image 169
KingCrunch Avatar answered Oct 02 '22 07:10

KingCrunch


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); } 
like image 22
Andreas Avatar answered Oct 02 '22 05:10

Andreas