Accessing substrings
Access substrings of a string by specifying a numerical
index inside square brackets. The index consists of one integer, optionally followed by a
comma and a second integer, for example $string[3]
or $string[3,10]
.
The first number of the index is the
start position. Positive numbers count from the start of the string, starting at
0
. Negative
numbers count back from the end of the string, starting at -1
.
The
second number of the index is the stop position. Positive numbers are lengths,
counting forward from the start position. Negative numbers are absolute positions,
counting back from the end of the string (starting at -1
). If the second number is omitted, it
defaults to 1
(resolving to a single character).
Examples:
$mystring = 'abcdef' notice( $mystring[0] ) # resolves to 'a' notice( $mystring[0,2] ) # resolves to 'ab' notice( $mystring[1,2] ) # resolves to 'bc' notice( $mystring[1,-2] ) # resolves to 'bcde' notice( $mystring[-3,2] ) # resolves to 'de'Text outside the actual range of the string is treated as an infinite amount of empty string:
$mystring = 'abcdef' notice( $mystring[10] ) # resolves to '' notice( $mystring[3,10] ) # resolves to 'def' notice( $mystring[-10,2] ) # resolves to '' notice( $mystring[-10,6] ) # resolves to 'ab'