【问题标题】:PHP Query - Check string characterPHP 查询 - 检查字符串字符
【发布时间】:2021-01-15 19:56:16
【问题描述】:
if (substr('xcazasd123', 0, 2) === 'ax'){
}

上面的代码正在工作,它能够检查“变量”是否是 从'ax'开始,但如果我想检查“多个”怎么办 不同的验证?

例如:'ax','ab','ac' ?无需创建多个 if 语句

【问题讨论】:

  • $value = substr('xcazasd123', 0, 2); $compare_array = array('ab','ax','ac'); if(in_array($value,$compare_array)){ // 运行你的代码 } 尝试在数组中使用

标签: php string-matching


【解决方案1】:

如果你想避免多个 if 语句,你可以使用数组来存储你的关键字,然后使用in_array()

$key_words =["ax","ab","ac"]
if (in_array( substr('yourstringvalue', 0, 2), $key_words ){
  //your code
}

参考资料: in_array — Checks if a value exists in an array

【讨论】:

    【解决方案2】:

    如果这个子字符串总是在同一个地方——简单快捷的是switch

    // $x = string to pass 
    switch(substr($x,0,2)){
        case 'ax':  /* do ax */ break;
        case 'ab':  /* do ab */ break;
        case 'ac':  /* do ac */ break;  // break breaks execution
        case 'zy':  /* do ZY */         // without a break this and next line will be executed
        case 'zz':  /* do ZZ */ break;  // for zz only ZZ will be executed
        default:    /* default proceed */}
    

    switchcase 中传递精确值 - 任何其他情况都是不可能的或奇怪和多余的。
    switch 还可以通过 default 评估另一个 switch 或其他条件

    manual

    【讨论】:

    • 谢谢,如果我有不同案例的多个场景,这是一个好方法,已经在我的笔记中,再次感谢。
    【解决方案3】:

    您可以使用 preg_match 方法来测试字符串:

    if(preg_match('/^(ax|ab|ac)/', '1abcd_test', $matches)) {
        echo "String starts with: " . $matches[1];
    } else {
        echo "String is not match";
    }
    

    示例:PHPize.online

    你可以通过更复杂的字符串匹配了解PHP Regular Expressions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-03
      相关资源
      最近更新 更多