PHP 查询 - 检查字符串字符
PHP Query - Check string character
if (substr('xcazasd123', 0, 2) === 'ax'){
}
Above code is working where it able to check if the "variable" is
starting with 'ax', but what if i wanted to check "multiple"
different validation ?
例如:'ax'、'ab'、'ac' ?不创建多个 if 语句
您可以使用数组来存储您的关键字,如果您想避免使用多个 if 语句,则可以使用 in_array()
。
$key_words =["ax","ab","ac"]
if (in_array( substr('yourstringvalue', 0, 2), $key_words ){
//your code
}
您可以使用 preg_match 方法来测试字符串:
if(preg_match('/^(ax|ab|ac)/', '1abcd_test', $matches)) {
echo "String starts with: " . $matches[1];
} else {
echo "String is not match";
}
您可以从更复杂的字符串匹配中了解PHP Regular Expressions
如果这个 sub-string 总是在同一个地方 - 简单快捷就是 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 */}
switch
在 case
中传递精确值 - 任何其他情况都不可能或奇怪和多余。
switch
也可以通过 default
评估到另一个 switch
或其他条件
if (substr('xcazasd123', 0, 2) === 'ax'){
}
Above code is working where it able to check if the "variable" is starting with 'ax', but what if i wanted to check "multiple" different validation ?
例如:'ax'、'ab'、'ac' ?不创建多个 if 语句
您可以使用数组来存储您的关键字,如果您想避免使用多个 if 语句,则可以使用 in_array()
。
$key_words =["ax","ab","ac"]
if (in_array( substr('yourstringvalue', 0, 2), $key_words ){
//your code
}
您可以使用 preg_match 方法来测试字符串:
if(preg_match('/^(ax|ab|ac)/', '1abcd_test', $matches)) {
echo "String starts with: " . $matches[1];
} else {
echo "String is not match";
}
您可以从更复杂的字符串匹配中了解PHP Regular Expressions
如果这个 sub-string 总是在同一个地方 - 简单快捷就是 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 */}
switch
在 case
中传递精确值 - 任何其他情况都不可能或奇怪和多余。
switch
也可以通过 default
评估到另一个 switch
或其他条件