Created
May 21, 2011 01:18
-
-
Save visualmotive/984118 to your computer and use it in GitHub Desktop.
String equivalents
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Python equivalent: | |
// string[start:end] | |
function tt_str_slice($string, $start=NULL, $end=NULL) { | |
$length = strlen($string); | |
if ($start === NULL) { | |
$start = 0; | |
} else if ($start < 0) { | |
$start = $length + $start; | |
if ($start < 0) { | |
$start = 0; | |
} | |
} | |
if ($end === NULL) { | |
$end = $length; | |
} else if ($end < 0) { | |
$end = $length + $end; | |
if ($end > $length) { | |
$end = $length; | |
} | |
} | |
if ($end <= $start) { | |
return ''; | |
} | |
return substr($string, $start, $end - $start); | |
} | |
// Python equivalent: | |
// string.startswith(value) | |
function tt_str_startswith($string, $value) { | |
if ($value === '') { | |
return TRUE; | |
} | |
return tt_str_slice($string, 0, strlen($value)) === $value; | |
} | |
// Python equivalent: | |
// string.endswith(value) | |
function tt_str_endswith($string, $value) { | |
if ($value === '') { | |
return TRUE; | |
} | |
return tt_str_slice($string, -strlen($value)) === $value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment