PHP strpos() visualized
Just because I can never keep this quite right in my brain...
strpos.php
<?php
$string = "12345|6789";
$sp = strpos($string, '|');
print "Position: $sp\n";
print "substr(..., $sp): " . substr( $string, $sp ) . "\n";
print "substr(..., 0, $sp): " . substr( $string, 0, $sp ) . "\n";
Output
Position: 5
substr(..., 5): |6789
substr(..., 0, 5): 12345
The string (char array) starts with position 0, and the 5th position contains the '|' character:
0 1 2 3 4 5 6 7 8 9
1 2 3 4 5 | 6 7 8 9
So, strpos($string, '|') returns 5
substr(string $string, int $offset, ?int $length = null) at an offset of '5' will start with the 5th position ('|') and go to $length if supplied, or the end of the string if not. Likewise, starting at an offset of 0 with a length of 5 will return the first 5 char values from the string, 12345.
Comments
Post a Comment