This function is to aide in parsing text files, and has proven useful for dealing with XML. This code is free to use for any purpose. A bit of credit in a readme file or about box would be great, but not necessary. VB and PHP versions are below.
strSource = The original string you wish to parse.
str1 = String that preceeds the value you wish to parse out.
str2 = String that follows the value you wish to parse out.
bCaseSensitive = When true, str1 and str2 must match the case of their values in strSource. This is true by default.
SomeStringArray = StrBetweenStrs("<tag>Woot</tag><tag>Woot again!</tag>", "<tag>", "</tag>")
Debug.Print SomeStringArray(0) 'Returns: Woot
Debug.Print SomeStringArray(1) 'Returns: Woot again!
Public Function StrBetweenStrs(strSource As String, str1 As String, str2 As String, Optional bCaseSensitive = True) As String() Dim pos1 As Long Dim pos2 As Long Dim results() As String Dim whatsleft As String Dim count As Integer whatsleft = strSource
Do While whatsleft <> "" If bCaseSensitive Then pos1 = InStr(1, whatsleft, str1) pos2 = InStr(pos1 + Len(str1), whatsleft, str2) Else pos1 = InStr(1, UCase(whatsleft), UCase(str1)) pos2 = InStr(pos1 + Len(str1), UCase(whatsleft), UCase(str2)) End If If pos1 = 0 Or pos2 = 0 Then Exit Do End If ReDim Preserve results(count) results(count) = Mid(whatsleft, pos1 + Len(str1), pos2 - (pos1 + Len(str1))) whatsleft = Right(whatsleft, Len(whatsleft) - pos2) count = count + 1 Loop StrBetweenStrs = results
End Function
function strbetweenstrs($strSource, $str1, $str2, $bCaseSensitive) {
$whatsleft=$strSource;
$count=0;
while ($whatsleft<>"") {
if ($bCaseSensitive) {
$pos1=strpos($whatsleft, $str1);
$pos2=strpos($whatsleft, $str2, $pos1+strlen($str1));
} else {
$pos1=strpos(strtoupper($whatsleft), strtoupper($str1));
$pos2=strpos(strtoupper($whatsleft), strtoupper($str2), $pos1+strlen($str1));
}
if (($pos1==0)||($pos2==0)) {
break;
}
$results[$count]=substr($whatsleft, $pos1+strlen($str1), $pos2-($pos1+strlen($str1)));
$whatsleft=substr($whatsleft,$pos2);
$count++;
}
return $results;
}