You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP开发:如何回显用户输入文本并替换错误提示语句

解决方案

没问题,这事儿很简单!你只需要在else分支的echo语句里直接引用$spec变量,就能把用户输入的文本插入到提示信息里了。

修改后的完整代码

<?php
// 假设$spec是你获取到的用户输入值,比如来自$_GET或$_POST
$spec = $_POST['spec']; // 示例,根据你的实际获取方式调整

if ( $spec == "Protection" || $spec == "Arms" || $spec == "Fury" || $spec == "Shadow" || $spec == "Discipline" || $spec == "Holy" || $spec == "Frost" || $spec == "Fire" || $spec == "Arcane" || $spec == "Destruction" || $spec == "Demonology" || $spec == "Affliction" || $spec == "Subtlety" || $spec == "Combat" || $spec == "Assassination" || $spec == "Restoration" || $spec == "Feral" || $spec == "Balance" || $spec == "Guardian" || $spec == "Enhancement" || $spec == "Restoration" || $spec == "Elemental" || $spec == "Marksmanship" || $spec == "Beast Mastery" || $spec == "Survival") { 
    echo "<br>"; 
    echo "Valid spec entered."; 
} else { 
    echo "<br>"; 
    echo "$spec is not a valid spec."; // 这里直接使用$spec变量
}
?>

额外优化建议

原来的条件判断太长了,维护起来很麻烦,你可以把所有有效的spec放到一个数组里,用in_array()函数来判断,代码会更简洁易读:

<?php
$validSpecs = [
    "Protection", "Arms", "Fury", 
    "Shadow", "Discipline", "Holy", 
    "Frost", "Fire", "Arcane", 
    "Destruction", "Demonology", "Affliction", 
    "Subtlety", "Combat", "Assassination", 
    "Restoration", "Feral", "Balance", "Guardian", 
    "Enhancement", "Elemental", 
    "Marksmanship", "Beast Mastery", "Survival"
];

$spec = $_POST['spec']; // 示例获取方式

if (in_array($spec, $validSpecs)) {
    echo "<br>Valid spec entered.";
} else {
    echo "<br>$spec is not a valid spec.";
}
?>

这样以后要添加或删除有效spec,直接修改数组就行,不用动条件判断的逻辑,方便多了。

内容的提问来源于stack exchange,提问作者Xellent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:27:58