【问题标题】:how to find out if the second character in a string is whitespace in php如何找出字符串中的第二个字符是否是php中的空格
【发布时间】:2019-01-03 19:36:13
【问题描述】:

我试图找出字符串中的第二个字符是否是空格。所以如果我有这个:

"a brown fox"

"hello world"

如何标记第一个字符串在第二个位置有空格,而第二个字符串没有?

【问题讨论】:

标签: php


【解决方案1】:

我可以想出多种方法来做到这一点,例如

Accessing string as an array

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
}

如果您已经计划将字符串分成多个部分,这将非常有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 2015-08-25
    • 2020-02-14
    相关资源
    最近更新 更多