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 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 " ten 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 Omitting the length argument is the same as if you had included 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 one that makes it 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 it is faster to replace a string with a string of equal length. |
|