【发布时间】:2019-01-03 19:36:13
【问题描述】:
我试图找出字符串中的第二个字符是否是空格。所以如果我有这个:
"a brown fox"
和
"hello world"
如何标记第一个字符串在第二个位置有空格,而第二个字符串没有?
【问题讨论】:
-
$string[1]将返回第二个字符,然后您只需将其与空格进行比较...
标签: php
我试图找出字符串中的第二个字符是否是空格。所以如果我有这个:
"a brown fox"
和
"hello world"
如何标记第一个字符串在第二个位置有空格,而第二个字符串没有?
【问题讨论】:
$string[1] 将返回第二个字符,然后您只需将其与空格进行比较...
标签: php
我可以想出多种方法来做到这一点,例如
if($string[1] == " ") {
//$string's 2nd character is a space
}
[1] 捕获字符串的第二个字母,因为它充当数组并且数组以键 0 开头。
如果您收到错误消息说该字符串不是数组或无效索引等,那么您可能需要将您的字符串拆分为一个数组,以便第一个工作。
if(str_split($string)[1] == " ") {
//$string's 2nd character is a space
}
substr()
与第一个示例类似,您也可以使用substr():
if(substr($string, 1, 1) == " ") {
//$string's 2nd character is a space
}
strpos()
同样,你可以使用strpos()
if(strpos("a brown fox", " ") == 1) {
//$string's 2nd character is a space
}
preg_match()
如果你愿意,你也可以使用正则表达式
if (preg_match('/^. /', $string)) {
//$string's 2nd character is a space
}
模式分解:
^ 在行首断言位置. 匹配任何字符(行终止符除外) 与字符字面匹配explode()
另一种公认的不太简单的方法是使用explode() 在空格处断开字符串,然后计算字符串在第一个空格之前的长度。
$string_parts = explode(" ", $string);
if(strlen($string_parts[0]) <= 1) {
//$string's 2nd character is a space
}
如果您已经计划将字符串分成多个部分,这将非常有用。
【讨论】: