在 PHP 开关中使用 strstr
我只是想不出代码。我有太多 if 语句,我想将其更改为 switch 语句,但我找不到逻辑。
目前我有:
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...
但是我怎样才能在交换机内实现相同的目标呢?
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.
At the moment I have:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请注意,这与您自己的解决方案略有不同,因为如果较早的情况已经匹配,则
switch
语句不会针对其他case
进行测试,而是因为您使用单独的if
,而不是 ifif-else
你的方式总是针对每种情况进行测试。Note, that this is slightly different to your own solution, because the
switch
-statement will not test against the othercase
s, if an earlier already matches, but because you use separateif
s, instead ifif-else
your way always tests against every case.我认为你无法使用
switch
(比现在更优雅)来实现这一点,因为它比较值,但你只想比较部分值。相反,你可以使用循环:I think you can't achieve this with
switch
(more elegant than now) because it compare values but you want compare only part of values. Instead you may use loop:你也可以用相反的方式来做:
You can do it the other way around: