本文介绍了在开关php中使用strstr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是想不出代码.我想将要更改为switch语句的陈述太多了,但我找不到逻辑.
I just cannot think of the code. I have waay too many if statments which I want to change to be a switch statement, but I cannot find of the logic.
目前,我有:
if(strstr($var,'texttosearch'))
echo 'string contains texttosearch';
if(strstr($var,'texttosearch1'))
echo 'string contains texttosearch1';
if(strstr($var,'texttosearch2'))
echo 'string contains texttosearc2h';
//etc etc...
但是我如何在交换机内实现相同的目标?
But how can I achieve the same within a switch?
推荐答案
switch (true) {
case strstr($var,'texttosearch'):
echo 'string contains texttosearch';
break;
case strstr($var,'texttosearch1'):
echo 'string contains texttosearch1';
break;
case strstr($var,'texttosearch2'):
echo 'string contains texttosearc2h';
break;
}
请注意,这与您自己的解决方案略有不同,因为switch
语句将不会针对其他case
进行测试(如果已匹配更早的版本),而是因为您使用了单独的if
如果if-else
您的方式总是针对每种情况进行测试.
Note, that this is slightly different to your own solution, because the switch
-statement will not test against the other case
s, if an earlier already matches, but because you use separate if
s, instead if if-else
your way always tests against every case.
这篇关于在开关php中使用strstr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!