简体   繁体   English

PHP-第一个和最后一个字符检查

[英]PHP - First and last character check

I am trying a check in PHP. 我正在尝试检查PHP。 What I want is to check: 我要检查的是:

  • The first character in a string must be a "[" 字符串中的第一个字符必须为“ [”
  • The last character in a string must be a "]" 字符串中的最后一个字符必须为“]”

I've written this code (last if statement is what I actually want) to check this but am not getting the result I wanted: 我已经编写了此代码(如果语句是我真正想要的,则是最后一个)来检查它,但没有得到我想要的结果:

$str = "dfgdfg]";

if($str[0] != '[') {
    echo "FIRST NOT EQUAL TO";
}

if(substr($str,-1) != ']') {
    echo "SECOND NOT EQUAL TO";
}


if( ($str[0] != '[') && (substr($str,-1) != ']') ) {
  echo "COND MET!";
}

If I run this code I thought that the last if statement would execute however, only the first if statement executes. 如果我运行此代码,我认为最后一条if语句将执行,但是只有第一个if语句将执行。 What is wrong with the logic in the last if statement? 最后一个if语句中的逻辑有什么问题?

You have the last statement set as "AND - && " and should be an "OR - ||" 您将最后一个语句设置为“ AND-&&”,并且应为“ OR-||”

if( ($str[0] != '[') || (substr($str,-1) != ']') ) {
echo "COND MET!";
}

Your final if statement is checking that the first character of your string is NOT a [ , and the last character is also NOT a ] . 你最终if语句检查你的字符串的第一个字符不是 [和最后一个字符也不是一个] If you remove the last ] from your $str , you'll see the COND MET output. 如果从$str删除最后一个] ,您将看到COND MET输出。

if( ($str[0] != '[') && (substr($str,-1) != ']') ) {
  echo "COND MET!";
}

If you want the check to ensure the string both starts and ends with a [ and ] , respectively, you need this: 如果要检查以确保字符串分别以[]开头和结尾,则需要这样做:

if( ($str[0] == '[') && (substr($str,-1) == ']') ) {
  echo "COND MET!";
}

简单的RegExr检查如何:

if (preg_match('/^\[.*\]$/', $str) {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM