在PHP中缩短多个elseif


Shorten multiple elseifs in PHP?

所以我想根据字符串包含的内容显示图像,并且我有多个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;
    }
}

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

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