以下是我要应用的9
个不同的字符串,如果还有条件(or something better
):
1. Automated - Under the Hood: iPhone 6 running iOS 9
2. Automated - AU/NZ: iPhone 6 running iOS 9
3. Automated - DRM: iPhone 6 running iOS 9
4. Automated - Ads regression: iPhone6 running iOS 9
5. Automated - Ads regression: iPhone 5 running iOS 8
6. Automated - UI & Functional Regression on iPad 2 running iOS 8
7. Automated - Under the Hood: iPad Air on iOS 8
8. Automated - AU/NZ: iPad Air running iOS 8
9. Automated - DRM iPadAir running iOS 8
每次,我都会获得一个above string
,并将其分配给PHP variable
。 It is possible that the order of words or position of few words in any string can change
。但有些事情比如OS, phone type, OS version and test type will not change
。根据字符串包含的具体单词,我将进行REST api调用。
例如,如果PHP var持有第一个字符串,即
$test = Automated - Under the Hood: iPhone 6 running iOS 9
,然后我将进行#1休息api通话。
所以,我认为我应该这样做的方式是:
if ($test/string contains "under", "hood", "iPhone 6", "iOS 9") then do #1rest call (that i have command for)
else if ($test/string contains "AU", "NZ", "iPhone 6", "iOS 9") then do #2rest call..
....
else
... for all the above 9 strings.
到目前为止,我在PHP中尝试过.contains()。 Will a switch be a better alternative to this? If yes, an example would be good to have.
否则,在if-else条件/正则表达式中更好的方法。
答案 0 :(得分:1)
您可以使用具有以下正则表达式的命名捕获组:
$re = "/-\s*(?<what>.*):.*?(?<device>ip(?:hone|ad(?: ?air)?))\s*(?<model>\d)?.*ios\s*(?<os>\d)/mi";
$strs = array(
"1. Automated - Under the Hood: iPhone 6 running iOS 9",
"2. Automated - AU/NZ: iPhone 6 running iOS 9",
"3. Automated - DRM: iPhone 6 running iOS 9 ",
"4. Automated - Ads regression: iPhone6 running iOS 9",
"5. Automated - Ads regression: iPhone 5 running iOS 8 ",
"6. Automated - UI & Functional Regression: on iPad 2 running iOS 8",
"7. Automated - Under the Hood: iPad Air on iOS 8",
"8. Automated - AU/NZ: iPad Air running iOS 8",
"9. Automated - DRM: iPadAir running iOS 8"
);
foreach($strs as $str)
{
preg_match_all($re, $str, $matches);
echo "What: " . $matches['what'][0] . "\n";
echo "Device: " . $matches['device'][0] . "\n";
echo "Device version: " . $matches['model'][0] . "\n";
echo "Os: " . $matches['os'][0] . "\n";
}
您可以在regex101
处尝试如果您想运行PHP:
matches['nameOfGroup'][0]
然后,您可以在if
条件中使用in_array
(例如,使用方法switch
)来执行您要运行的代码。
在std::basic_string
或大if / else条件之间进行选择将取决于您的代码以及您希望根据结果执行的方法。