在PHP中缩短多个elseif?

在PHP中缩短多个elseif?,php,if-statement,strpos,Php,If Statement,Strpos,所以我想根据字符串包含的内容显示一个图像,并且我有多个elseif?我已经把它缩短了一点,但现在是50多行。我在想一定有更干净的方法可以做到这一点 <?php if(strpos(' '.$this->escape($title).' ', '25% off')){$imgsrc = '25percentoff.png';} elseif(strpos(' '.$this->escape($title).' ', '24% off')){$imgsrc =

所以我想根据字符串包含的内容显示一个图像,并且我有多个elseif?我已经把它缩短了一点,但现在是50多行。我在想一定有更干净的方法可以做到这一点

   <?php if(strpos(' '.$this->escape($title).' ', '25% off')){$imgsrc = '25percentoff.png';}
        elseif(strpos(' '.$this->escape($title).' ', '24% off')){$imgsrc = '24percentoff.png';}
        elseif(strpos(' '.$this->escape($title).' ', '23% off')){$imgsrc = '23percentoff.png';}
        elseif(strpos(' '.$this->escape($title).' ', '22% off')){$imgsrc = '22percentoff.png';}
        elseif(strpos(' '.$this->escape($title).' ', '21% off')){$imgsrc = '21percentoff.png';}
        elseif(strpos(' '.$this->escape($title).' ', '20% off')){$imgsrc = '20percentoff.png';}
        elseif(strpos(' '.$this->escape($title).' ', '19% off')){$imgsrc = '19percentoff.png';}
        else{$imgsrc = 'default.png';}
   ?>

这是一种解决方案:

$imgsrc = 'default.png';
for ( $percent=100; $percent>0; $percent--) {
    if(strpos($this->escape($title), $percent . '% off') !== false){
        $imgsrc = $percent . 'percentoff.png';
        break;
    }
}
这是一个解决方案:

$imgsrc = 'default.png';
for ( $percent=100; $percent>0; $percent--) {
    if(strpos($this->escape($title), $percent . '% off') !== false){
        $imgsrc = $percent . 'percentoff.png';
        break;
    }
}

如果您不知道
$title
包含的内容,仍然可以使用正则表达式匹配百分比:

<?php

if(preg_match('/^([1-9][0-9]?|100)% off/', $this->escape($title), $matches)) {
  $imgsrc = $matches[1] . 'percentoff.png';
} else {
  $imgsrc = 'default.png';
}

如果您不知道
$title
包含什么,您仍然可以使用正则表达式匹配百分比数字:

<?php

if(preg_match('/^([1-9][0-9]?|100)% off/', $this->escape($title), $matches)) {
  $imgsrc = $matches[1] . 'percentoff.png';
} else {
  $imgsrc = 'default.png';
}


use switch case statement为什么在标题前后添加空格?因为如果字符串以我试图查找的内容开头,显然
strpos
不匹配。@MikeMade:它会,但它会返回
0
,因此您的比较必须是
!==错误
,而不仅仅是
@MikeMeade胡说八道。它只返回
0
,因为它从索引
0
开始。您只需要考虑到这一点,比如
if(strpos(…)!==false)
。使用switch case语句为什么要在标题前后添加空格?因为如果字符串以我试图查找的内容开头,显然
strpos
不匹配。@mikemade:它会,但它会返回
0
,因此您的比较必须是
!==错误
,而不仅仅是
@MikeMeade胡说八道。它只返回
0
,因为它从索引
0
开始。你只需要考虑到这一点,比如
if(strpos(…)!==false)
。完美!就是那张票!完美的就是那张票!我可以添加一个限制来验证$matches[1]是否位于边界(如1和100)之间,否则可以使用10000Percentof.png。@Danbopes:是的,这取决于$title
的来源以及它是否可以包含超出范围的数字。Mike没有具体说明。他提到了50+行,这意味着限制了可能的数量。好的,增加了1-100个范围。很好,我真的很喜欢这个解决方案。我会添加手动if/else语句。(但这更好)我可以添加一个限制来验证$matches[1]是否位于1和100之间,否则可以使用10000Percentof.png。@Danbopes:是的,这取决于
$title
来自何处以及它是否可以包含超出范围的数字。Mike没有具体说明。他提到了50+行,这意味着限制了可能的数量。好的,增加了1-100个范围。很好,我真的很喜欢这个解决方案。我会添加手动if/else语句。(但这要好得多)