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]
[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]