Forum Moderators: coopster
Say I have a text file with the following data:
<begintoken>username<endtoken>
<begintoken>username2<endtoken>
<begintoken>username3<endtoken>
I'd like to get an array where each element of the array consists of the text between the token strings.
Something like this:
$array=extractData($string,$begin,$end);
echo $array[1] would return "username"
echo $array[2] would return "username2"
echo $array[3] would return "username3"
Are there any functions that do this out of the box? Am I just overlooking one of the basic PHP String functions?
It would be easier if the string were in the form:
username<token>username2<token>username3
Then to convert to array it's just one line:
$ary = explode('<token>',$s);
The while loop iterates through each of the elements in the array. $i gets the index of the element and $s gets the contents of the element, so first pass:
$i = 0
$s = '<begintoken>username'
Then the next line uses the substring function to ignore the first x characters (the length of the token), and puts it back into the array generated by the explode.
So on first pass,
$sa[0] = 'username'
In other words, what if my file contains:
<begintoken1>username</endtoken>
<begintoken2>description</endtoken>
<begintoken1>username</endtoken>
<begintoken2>description</endtoken>
So notice that the endtokens are the same, and the only indicator of difference is the begin token.
Unfortunately, this is the situation I'm in (wish the begin and end tokens were both original).
Find the first begintoken then find the first endtoken immediately proceeding it, then extract the data between the two points?
In PHP is there a built in function that returns the first instance of any given string token (rather than the last instance)? Or is there something that achieves this pseudocode:
foreach($begintoken in $string){
extractStringBetween($begintoken and $firstoccurrenceofendtoken within $string);
}