Reputation: 878
I've got such a string:
$string = "Serving Time: 5mins
Cooking time 10 mins
Servings 4
Author: Somebody
Directions
1...
2..."
I want to get output of Cooking time, it means closest digit to phrase: "Cooking time" and also I want to get closes digit to phrase "Servings"
So output would be
$serves = some_kind_of_function($string);
$serves == 4; //true
$cookingtime = some_kind_of_function($string);
$cookingtime == 10 //true
What would be best way of acquiring that?
Thanks!
Adam
Upvotes: 3
Views: 62
Reputation: 784998
You can use this search like this:
function findNum ( $str, $search ) {
if ( preg_match("/" . preg_quote($search, '/') . "\D*\K\d+/i", $str, $m) )
return $m[0];
return false;
}
$str = "Serving Time: 5mins
Cooking time 10 mins
Servings 4
Author: Somebody
Directions
1...
2...";
findNum( $str, "Cooking" ); // 10
findNum( $str, "Servings" ); // 4
Upvotes: 2
Reputation: 2128
you can convert it to an array
by replacing space
between the words by ,(comma)
by using this function
$array = explode(' ', $string);
now
$count = count($array);
for($i=0;$i<$count;$i++)
{
if($array[$i]=='servings')
{
$serves = $array[$i+1]
}
if($array[$i]=='time')
{
$cookingtime= $array[$i+1]
}
}
echo $serves;
echo $cookingtime." Minutes";
please let me know if you have any issue.
Upvotes: 1