使用PHP获取单词的第一个字母

使用PHP获取单词的第一个字母,php,Php,如果变量前面包含S,是否可以设置变量验证 我的代码中的示例: $a = "S0225"; $b = "700S4"; if(strpos($a, 'S') !== FALSE) { echo "PASS"; //for this It will pass } if(strpos($b, 'S') !== FALSE) { echo "PASS"; //for this, why this pass too, whereas I want just value

如果变量前面包含S,是否可以设置变量验证

我的代码中的示例:

$a = "S0225";
$b = "700S4";

if(strpos($a, 'S') !== FALSE) {
    echo "PASS";
    //for this It will pass
}

if(strpos($b, 'S') !== FALSE) {
    echo "PASS";
    //for this, why this pass too, whereas I want just value of variable start front S
}

改为这样检查

if(strpos($b, 'S')==0)  //<---- Check for position instead of boolean
{
    echo $b; // Will not print..
}
试一试

if(strpos($b, 'S') == 0) {
    echo "PASS";
}
您也可以使用substr之类的工具进行尝试

返回针相对于干草堆字符串开头的位置,与偏移无关。还要注意,字符串位置从0开始,而不是从1开始

如果未找到指针,则返回FALSE

因此,为了确保S位于字符串的开头,这意味着S应该位于位置0处

// Note our use of ===.  Simply == would not work as expected
// because the position of 'S' is the 0th (first) character.
// this will make sure that it is also comparing it with an Integer.
if(strpos($a, 'S') === 0)
{
  echo "PASS";
}
文档中的警告:

此函数可能返回布尔值FALSE,但也可能返回 计算结果为FALSE的非布尔值。请阅读关于 更多信息请参见布尔值。使用===运算符测试 此函数的返回值

您也可以为此目的使用

if(substr($string_goes_here, 0, 1) === 'S') {
    //Pass
}
if(substr($string_goes_here, 0, 1) === 'S') {
    //Pass
}