如何检查一个字符串是否以指定的字符串开头?


This question already has an answer here:

我试图检查一个字符串是否以http开头。我该如何做这个检查?

$string1 = 'google.com';
$string2 = 'http://www.google.com';
substr( $string_n, 0, 4 ) === "http"

如果你想确保它不是另一个协议。我会使用http://来代替,因为https也可以匹配,而其他的东西如http-protocol.com。

substr( $string_n, 0, 7 ) === "http://"

一般来说:

substr($string, 0, strlen($query)) === $query

使用strpos()

if (strpos($string2, 'http') === 0) {
   // It starts with 'http'
}

记住三个等号(===)。如果只使用两个,它将无法正常工作。这是因为如果无法在干草堆中找到针,strpos()将返回false

未经作者同意,本文严禁转载,违者必究!