Sunday, December 31, 2006

Mimic python

After the article yesterday i decided to mimic the python behaviour for strings and arrays.
Below you find the function to get parts from a string or an array. I added a '1,5,4' limiter to get specific and/or loose parts.

function getStrArr($var,$limiter){
if(is_numeric($limiter)){
// get one value
if(strpos($limiter,'-') === false){
return (is_array($var))?$var[$limiter]:substr($var,$limiter,1);
// get last value(s)
}else{
return (is_array($var))? array_slice($var,$limiter) : substr($var,strlen($var)+$limiter) ;
}
}else{
if(strpos($limiter,',') === false){
if(strpos($limiter,':') == 0){
$lim = str_replace(':','',$limiter);
// get part from the begin
if(strpos($limiter,'-') === false){
return (is_array($var))?array_slice($var,0,$lim):substr($var,0,$lim);
// get part from the end
}else{
return (is_array($var))? array_slice($var,$lim) : substr($var,strlen($var)+$lim);
}
}else{
$temp = explode(':',$limiter);
if($temp[1] == ''){
// exclude part from begin
if(strpos($limiter,'-') === false){
return (is_array($var))?array_slice($var,$temp[0]):substr($var,$temp[0]);
// exclude part from the end
}else{
return (is_array($var))? array_slice($var,0,count($var)+$temp[0]) : substr($var,0,strlen($var)+$temp[0]);
}
}else{
// get self defined part
$min = $temp[1]-$temp[0];
return (is_array($var))? array_slice($var,$temp[0],$min) : substr($var,$temp[0],$min);
}
}
}else{
// get pieces
$temp = explode(',',$limiter);
if(is_array($var)){
$arr = array();
foreach($temp as $t){ $arr[] = $var[$t]; }
return $arr;
}else{
$str = '';
foreach($temp as $t){ $str .= substr($var,$t,1); }
return $str;
}
}
}
}

No comments: