如果 else 语句中的多个字符串错误


Multiple string bug in if else statement

if($title=="Random 1.5"){ //value1
    $ytitle = "Custom 1.5"; 
    }
else if($title=="Another 1.6"){ //value2
    $ytitle = "Custom 1.6";
    }
else if($title=="Bold Random 1.5"){ //value3
    $ytitle = "Custom 1.7";
    }   

值 1 和值 3 正在检索 True,因为(随机 1.5(在字符串中。 如何解决这个问题?我只想发布粗体随机 1.5 值。谢谢你的帮助。

您正在执行完全字符串匹配,而不是子字符串匹配,因此除非您的$title值与 if(( 语句中的字符串完全相同,否则您的"随机 1.5"和"粗体随机 1.5"不可能匹配相同。

例如

$teststring = 'Random 1.5';
($teststring == 'Random 1.5') // evaluates to TRUE
($teststring == 'Bold Random 1.5') // evaluates to FALSE

但如果你有

strpos('Random 1.5', $teststring) // integer 0 result, not boolean false
strpos('Bold Random 1.5', $teststring) // integer 4 result, not boolean false

两者都会成功,因为"随机 1.5"出现在正在搜索的两个字符串中。

同样,由于您要针对多个值反复测试一个变量,请考虑改用 switch((:

switch($title) {
   case 'Random 1.5':      $ytitle = 'Custom 1.5'; break;
   case 'Another 1.6':     $ytitle = 'Custom 1.6'; break;
   case 'Bold Random 1.5': $ytitle = 'Custom 1.7'; break;
}