$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?
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 .
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.
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.
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.
It's just math
$sub = substr($str, 3, 5 - 3);
The length is the end minus the start.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With