Voting

: seven minus zero?
(Example: nine)

The Note You're Voting On

slow at acedsl dot com
14 years ago
Anyone coming from the Python world will be accustomed to making substrings by using a "slice index" on a string. The following function emulates basic Python string slice behavior. (A more elaborate version could be made to support array input as well as string, and the optional third "step" argument.)

<?php

function py_slice($input, $slice) {
$arg = explode(':', $slice);
$start = intval($arg[0]);
if (
$start < 0) {
$start += strlen($input);
}
if (
count($arg) === 1) {
return
substr($input, $start, 1);
}
if (
trim($arg[1]) === '') {
return
substr($input, $start);
}
$end = intval($arg[1]);
if (
$end < 0) {
$end += strlen($input);
}
return
substr($input, $start, $end - $start);
}

print
py_slice('abcdefg', '2') . "\n";
print
py_slice('abcdefg', '2:4') . "\n";
print
py_slice('abcdefg', '2:') . "\n";
print
py_slice('abcdefg', ':4') . "\n";
print
py_slice('abcdefg', ':-3') . "\n";
print
py_slice('abcdefg', '-3:') . "\n";

?>

The $slice parameter can be a single character index, or a range separated by a colon. The start of the range is inclusive and the end is exclusive, which may be counterintuitive. (Eg, py_slice('abcdefg', '2:4') yields 'cd' not 'cde'). A negative range value means to count from the end of the string instead of the beginning. Both the start and end of the range may be omitted; the start defaults to 0 and the end defaults to the total length of the input.

The output from the examples:
c
cd
cdefg
abcd
abcd
efg

<< Back to user notes page

To Top