user3142825
user3142825

Reputation: 37

PHP - Shorten Sentence in a String If a Certain Word in an Array is Found

I am working on a PHP script which gets a METAR report and clears it up. I need to shorten the METAR by deleting everything that follows if certain words are used.

For example, I need to delete everything after BECMG including the space in front of TEMPO in the following string as it is not needed:

$metars = "2013/12/24 07:30 NZOH 240730Z 31011G21KT 280V340 5000 -SHRA FEW020 BKN048 19/14 Q1006 BECMG 20KM TEMPO 6000 RA BKN012 SPECI COR NZOH 240730Z 31011G21KT 280V340 5000 -SHRA FEW020 BKN048 19/14 Q1006 BECMG 20KM TEMPO 6000 RA BKN012";

$comments = array ("BECMG", "RMK", "TEMPO");

$metar = ???

I need $metar to be:

$metar = "2013/12/24 07:30 NZOH 240730Z 31011G21KT 280V340 5000 -SHRA FEW020 BKN048 19/14 Q1006";

There lies the problem. I can't use length numbers as the length can change. How can I delete everything after a certain word is found out of an array of words including the space in front of the word to shorten the string?

Also, $metars includes BECMG and TEMPO. How can I avoid having $metar include BECMG if it is shortened after another word is found? In other words, I want ot avoid this from happening:

$metar = "2013/12/24 07:30 NZOH 240730Z 31011G21KT 280V340 5000 -SHRA FEW020 BKN048 19/14 Q1006 BECMG 20KM";

I want it to be:

$metar = "2013/12/24 07:30 NZOH 240730Z 31011G21KT 280V340 5000 -SHRA FEW020 BKN048 19/14 Q1006";

Upvotes: 0

Views: 110

Answers (1)

user2680766
user2680766

Reputation:

You may use a foreach loop and string functions like strpos and substr to achieve what you need:

$metar = "2013/12/24 07:30 NZOH 240730Z 31011G21KT 280V340 5000 -SHRA FEW020 BKN048 19/14 Q1006 BECMG 20KM TEMPO 6000 RA BKN012 SPECI COR NZOH 240730Z 31011G21KT 280V340 5000 -SHRA FEW020 BKN048 19/14 Q1006 BECMG 20KM TEMPO 6000 RA BKN012";
$comments = array ("BECMG", "RMK", "TEMPO");
foreach($comments as $comment){
$pos = strpos($metar, " ".$comment);
if($pos !== false)
$metar = substr($metar, 0, $pos);
}
// Now $metar is "2013/12/24 07:30 NZOH 240730Z 31011G21KT 280V340 5000 -SHRA FEW020 BKN048 19/14 Q1006"

Upvotes: 2

Related Questions