I have some code which scrapes a string between two other strings (sandwich). It is working - but I need to loop through various "sandwich" strings.
//needle in haystack
$result 'sandwich: Today is a nice day.
sandwich: Today is a cloudy day.
sandwich: Today is a rainy day.
sandwich type 2: Yesterday I had an awesome time.
sandwich type 2: Yesterday I had an great time.';
$beginString = 'today is a';
$endString = 'day';
function extract_unit($haystack, $keyword1, $keyword2) {
$return = array();
while($a = strpos($haystack, $keyword1, $a)) { // loop until $a is FALSE
$a+=strlen($keyword1); // set offset to after $keyword1 word
if($b = strpos($haystack, $keyword2, $a)) { // if found $keyword2 position's
$return[] = trim(substr($haystack, $a, $b-$a)); // put result to $return array
}
}
return $return;
}
$text = $result;
$unit = extract_unit($text, $beginString, $endString);
print_r($unit);
//$unit returns= nice, cloudy and rainy
I need to loop through different types of sentences/sandwiches and be able to capture all the adjectives (nice cloudy rainy awesome great):
//needle in haystack
$result 'sandwich: Today is a nice day.
sandwich: Today is a cloudy day.
sandwich: Today is a rainy day.
sandwich type 2: Yesterday I had an awesome time.
sandwich type 2: Yesterday I had an great time.';
$beginString1 = 'today is a';
$endString1 = 'day';
$beginString2 = 'Yesterday I had an';
$endString2 = 'time';
[scaping code with loop...]
print_r($unit);
This is the goal to end up with this array:
Array ( [0] => nice [1] => cloudy [2] => rainy [3] => awesome [4] => great )
Any ideas? Much appreciated.