note 103143 added to function.substr

From: Date: Mon, 28 Mar 2011 21:47:37 +0000
Subject: note 103143 added to function.substr
Groups: php.notes 
Request: Send a blank email to php-notes+get-178282@lists.php.net to get a copy of this message
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 ---- Server IP: 64.71.164.2 Probable Submitter: 66.114.70.139 ---- Manual Page -- http://www.php.net/manual/en/function.substr.php Edit -- https://master.php.net/note/edit/103143 Del: integrated -- https://master.php.net/note/delete/103143/integrated Del: useless -- https://master.php.net/note/delete/103143/useless Del: bad code -- https://master.php.net/note/delete/103143/bad+code Del: spam -- https://master.php.net/note/delete/103143/spam Del: non-english -- https://master.php.net/note/delete/103143/non-english Del: in docs -- https://master.php.net/note/delete/103143/in+docs Del: other reasons-- https://master.php.net/note/delete/103143 Reject -- https://master.php.net/note/reject/103143 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#178282) next »