Reputation: 119
I'm trying to use strpos() to search a PHP string for specific words, as part of a function to sniff out a user's U.S. military service and display a message thanking them for their service. The problem is, for U.S. Air Force (USAF) veterans, the message appears twice because it also sniffs out the "USA" portion (which is a separate acronym for U.S. Army veterans.)
$p1Name = "Mr. John Smith";
$p2Name = "SSgt. John Doe, USAF";
$milbranches = array("USAF", "USMC", "USCG", "USN", "USA");
foreach ($milbranches as $mil)
{
if(strpos($p1Name, $mil) !== FALSE OR strpos($p2Name, $mil) !== FALSE)
{
echo "Thank you for your service.";
}
}
The OR statement to sniff this out from either $p1Name
or $p2Name
appears to work fine, but because $p2Name
in this instance contains USAF
, therefore satisfying a match for both USAF
and USA
, this yields the output of:
Thank you for your service.Thank you for your service.
There has to be something, maybe with preg_match() (I'm very unfamiliar with string comparison in PHP) or something that can tell it to only pay attention to the entirety of the phrase, and not pick out individual characters that are a match?
Thank you!
Upvotes: 1
Views: 43
Reputation: 5838
Break the foreach loop when it hits the first coincidence.
$p1Name = "Mr. John Smith";
$p2Name = "SSgt. John Doe, USAF";
$milbranches = array("USAF", "USMC", "USCG", "USN", "USA");
foreach ($milbranches as $mil)
{
if(strpos($p1Name, $mil) !== FALSE OR strpos($p2Name, $mil) !== FALSE)
{
echo "Thank you for your service.";
break;
}
}
Upvotes: 3