SRL Archive - Web Development

isolateEnclosedSubstring();


freyyr

2007-07-07 13:06:19

Just a function I whipped up. It's useful for when you're trying to parse a variable length substring in a document. If you know the contents of two surrounding substrings, you can isolate the middle one.

[PHP]function isolateEnclosedSubstring($precedingDiamond, $suceedingDiamond, $rough)
{
$precedingDiamondPos = strpos($rough, $precedingDiamond) + strlen($precedingDiamond);
$suceedingDiamondPos = strpos($rough, $suceedingDiamond, $precedingDiamondPos);
$nuggetLen = $suceedingDiamondPos - $precedingDiamondPos;
$nugget = substr($rough, $precedingDiamondPos, $nuggetLen);
return $nugget;
}[/PHP]

For instance, let's say you have this string, stored as $theRussiansareComing:
Counterattack Strategy: Retaliatory strike
Presidential Order: Initiate Launch Procedures


and you want to get the counterattack strategy, which can vary in number of characters. To do this, use:

[php]isolateEnclosedSubstring('Strategy: ', 'Presidential', $theRussiansareComing);[/php]

Ron

2007-07-21 23:20:39

Nice function man. I made my own in order to parse a string to display the RS High Scores; it really came in handy.

Anyway here's mine. I called it str_between though. :)

// function to get the string in between 2 other strings.
// made by Ron :)
function str_between($str, $betw, $betw2)
{
$str = " " . $str;
$pos = strpos($str, $betw);
if ($pos > 0)
{
$str2 = substr($str, $pos + strlen($betw));
$pos2 = strpos($str2, $betw2);
if ($pos2 == 0)
return '';
return substr($str2, 0, $pos2);
}
else
return '';
}

While using my function I came under problems like, what if each of the strings I supplied for the $betw and $betw2 were the same or what if one did not exist, what should the function do? So the function got a little longer. I'm not sure if your function does the same, but in case you're using yours, you might want to test it. Just for the hell of it. :)

~Ron