substr() Vs. substring()
The substr() method extracts a portion of a string based on the starting index and a specified length. The parameters are the starting index and the number of characters to extract.
If the length parameter is omitted, the method extracts characters from the starting index to the end of the string.
The substring() method also extracts a portion of a string, but it uses two indices as parameters: the starting index and the ending index (exclusive). It always extracts characters between the two indices.
If the starting index is greater than the ending index, substring() swaps the indices, ensuring that the substring is extracted correctly.
- substr() uses the starting index and length as parameters, while substring() uses the starting and ending indices.
- Negative indices in substr() count from the end of the string, whereas in substring(), negative indices are treated as 0.
- If the length parameter in substr() is negative, it's treated as 0. In substring(), if either index is negative or greater than the string length, they are treated as 0.
While both methods are used to extract substrings, substr() uses the starting index and length, while substring() uses the starting and ending indices. The choice between them depends on your specific requirements for substring extraction.