The closest number in a line to a specific phrase

I have a line like this:

$string = "Serving Time: 5mins
Cooking time 10 mins
Servings 4
Author: Somebody

Directions

1...
2..."

I want to get out of Cooking time, this means that the closest digit to the phrase: "Cooking time", and I also want to get a digit for the phrase "Services"

So the conclusion will be

$serves = some_kind_of_function($string);
$serves == 4; //true

$cookingtime = some_kind_of_function($string);
$cookingtime == 10 //true

What is the best way to get this?

Thank!
Adam

+3
source share
2 answers

You can use this search as follows:

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
+2
source

you can convert it to arrayby replacing spacebetween words ,(comma) 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 problems.

+1
source

All Articles