Link to home
Start Free TrialLog in
Avatar of onlinerack
onlinerackFlag for United States of America

asked on

php script to find a matching word and parse the number after it in a variable

I have a script that breaks down each line by itself, what I need to do is to have the php script to look at each line and if the first word = NTP: then to get the number after it and assign it echo that number only.

so say you have these three lines
$data= "ORDER 5434 processed on time
 NTP: +44332.43 was accepted
 UTC: +5 approved";

so if I pass these three lines in, it should catch that NTP: and print +44332.43

what is the best way to do it. It is simple but there are so many string functions I do not know which to use and I have been a bit rusty.
Avatar of hielo
hielo
Flag of Wallis and Futuna image

preg_match('#NTP:\s+(.+)#', $data,$match);
print_r($match);
Avatar of onlinerack

ASKER

the + can also be a -  and I would like that to be captured and be displayed.
preg_match('#NTP:\s+([+-]\S+)#', $data,$match);
print_r($match);
Here's a demo of one way to do it.  Displays the whole string first and then extracts the value after NTP:.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<title>Order Process</title>
</head>
<body>
<?php 
$data= "ORDER 5434 processed on time
 NTP: +44332.43 was accepted
 UTC: +5 approved";

 echo $data."<br><br>";
 $pieces = explode(" ", $data);
 reset($pieces);
 $ii = 9; // something greater than 0
while (list(, $value) = each($pieces)) {
    $ii++;
		if(strcmp("NTP:",$value) == 0) $ii = 0;
		if($ii == 1) { 
			echo $value;
			break;
			}
	}

 ?>
</body>
</html>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I will give that a try and let you know tomorrow... thank you very much guys.

if I can add one twist would be nice but this is optional if too much work do not worry about it.

say I have 6 lines, with multiple NTP: how would you word to catch the numbers:

$data="ORDER 5434 processed on time
 NTP: +44332.43 was accepted
 UTC: +5 approved
ORDER 5434 processed on time
 NTP: -0.3223.43 was accepted
 UTC: +6 approved";
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you, I was able to take your recommendations and modify my script based on your recommendations which lead me to the solution.... very much appreciated.