Jump to content

function to cut strings


madrazel

Recommended Posts

i just made this little fella:

 


function strcut($x,$y,$z) {
if ($z=="<-") return strstr($x,$y);
if ($z=="(-") return substr(strstr($x,$y),strlen($y),strlen($x));
if ($z=="->") return strrev(strstr(strrev($x),strrev($y)));
if ($z=="-)") return strrev(substr(strstr(strrev($x),strrev($y)),strlen($y),strlen($x)));
if ($z=="<") return $y.strrev(substr(strrev($x),0,strpos($x,$y)));
if ($z=="(") return strrev(substr(strrev($x),0,strpos($x,$y)));
if ($z==">") return substr($x,0,strpos($x,$y)).$y;
if ($z==")") return substr($x,0,strpos($x,$y));
};

echo strcut("abcXYdefXYghi","XY",")");


 

it works like this:

string: abcXYdefXYghi

 

<- = XYdefXYghi
(- = defXYghi
-> = abcXYdefXY
-) = abcXYdef
< = XYghi
( = ghi
> = abcXY
) = abc

 

any ideas to improve it ?

Link to comment
https://forums.phpfreaks.com/topic/48434-function-to-cut-strings/
Share on other sites

sorry, i forgot...

 

function strcut($x,$y,$z) {
if ($z=="<-") { return strstr($x,$y); }
elseif ($z=="(-") {return substr(strstr($x,$y),strlen($y),strlen($x));}
elseif ($z=="->") {return strrev(strstr(strrev($x),strrev($y)));}
elseif ($z=="-)") {return strrev(substr(strstr(strrev($x),strrev($y)),strlen($y),strlen($x)));}
elseif ($z=="<") {return $y.strrev(substr(strrev($x),0,strpos($x,$y)));}
elseif ($z=="(") {return strrev(substr(strrev($x),0,strpos($x,$y)));}
elseif ($z==">") {return substr($x,0,strpos($x,$y)).$y;}
elseif ($z==")") {return substr($x,0,strpos($x,$y));}
};

ok, now i done it,:

 

// x - haystack, y - needle, z - mode
function strcut($x,$y,$z) {
switch ($z) {
case '<-': return strstr($x,$y);
case '(-': return substr(strstr($x,$y),strlen($y),strlen($x));
case '->': return strrev(strstr(strrev($x),strrev($y)));
case '-)': return strrev(substr(strstr(strrev($x),strrev($y)),strlen($y),strlen($x)));
case '<' : return $y.strrev(substr(strrev($x),0,strpos($x,$y)));
case '(' : return strrev(substr(strrev($x),0,strpos($x,$y)));
case '>' : return substr($x,0,strpos($x,$y)).$y;
case ')' : return substr($x,0,strpos($x,$y));
default  :  echo "ERROR IN STRCUT"; break;};
};

//testing
$z = array('<-','(-','->','-)','<','(','>',')',);
$x = '123-XY-456-XY-789';
foreach ($z as $z) { echo $z.'  =   '.strcut($x,'XY',$z)."\n"; }

//output
//<-  =   XY-456-XY-789
//(-  =   -456-XY-789
//->  =   123-XY-456-XY
//-)  =   123-XY-456-
//<  =   XY-789
//(  =   -789
//>  =   123-XY
//)  =   123-

 

the question is actually about particular expresiions, i want to avoit things like these:

strrev(substr(strstr(strrev($x),strrev($y)),strlen($y),strlen($x)))

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.