Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closest number in string to specific phrase

Tags:

string

regex

php

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

like image 970
Adam Lesniak Avatar asked Nov 18 '25 08:11

Adam Lesniak


1 Answers

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
like image 142
anubhava Avatar answered Nov 20 '25 22:11

anubhava