15.2 Extracting and Replacing a Substring
Pulling out a piece of a string can be done with careful application of regular expressions, but if the piece is always at a known character position, this method is inefficient. Instead, you should use
$s = substr(
The start position works like $hello = "hello, world!"; $grab = substr($hello, 3, 2); # $grab gets "lo" $grab = substr($hello, 7, 100); # 7 to end, or "world!" You could even create a " 10 to the power of " operator for small integer powers, as in: $big = substr("10000000000",0,$power+1); # 10**$power
If the count of characters is zero, an empty string is returned. If either the starting position or ending position is less than zero, the position is counted that many characters from the end of the string. So $stuff = substr("a very long string",-3,3); # last three chars $stuff = substr("a very long string",-3,1); # the letter "i"
If the starting position is before the beginning of the string (like a huge negative number bigger than the length of the string), the beginning of the string is the start position (as if you had used zero for a starting position). If the start position is a huge positive number, the empty string is always returned. In other words, Omitting the length argument provides the same result as including a huge number for that argument - grabbing everything from the selected position to the end of the string.[ 1 ]
If the first argument to
What gets changed as the result of such an assignment is the part of the string that would have been returned had the $hw = "hello world!"; substr($hw, 0, 5) = "howdy"; # $hw is now "howdy world!"
The length of the replacement text (what gets assigned into the substr($hw, 0, 5) = "hi"; # $hw is now "hi world!" and here's an example that makes the string longer: substr($hw, -6, 5) = "nationwide news"; # replaces "world" The shrinking and growing are fairly efficient, so don't worry about using them arbitrarily, although replacing a string with a string of equal length is a faster solution. |
|