我试图检查字符串是否以http开头。我该怎么核对呢?

$string1 = 'google.com';
$string2 = 'http://www.google.com';

当前回答

PHP 8或更新版本:

使用str_starts_with函数:

str_starts_with('http://www.google.com', 'http')

PHP 7或更高版本:

使用substr函数返回字符串的一部分。

substr( $string_n, 0, 4 ) === "http"

如果你想确保这不是另一种协议。我将使用http://代替,因为https也会匹配,以及其他东西,如http-protocol.com。

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

总的来说:

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

其他回答

还有strncmp()函数和strncasecmp()函数,它们非常适合这种情况:

if (strncmp($string_n, "http", 4) === 0)

一般来说:

if (strncmp($string_n, $prefix, strlen($prefix)) === 0)

与substr()方法相比,strncmp()方法的优点是只做需要做的事情,而不创建临时字符串。

PHP 8或更新版本:

使用str_starts_with函数:

str_starts_with('http://www.google.com', 'http')

PHP 7或更高版本:

使用substr函数返回字符串的一部分。

substr( $string_n, 0, 4 ) === "http"

如果你想确保这不是另一种协议。我将使用http://代替,因为https也会匹配,以及其他东西,如http-protocol.com。

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

总的来说:

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

您可以使用一个简单的regex(由viriathus用户提供的更新版本,因为已弃用eregi)

if (preg_match('#^http#', $url) === 1) {
    // Starts with http (case sensitive).
}

或者如果你想要不区分大小写的搜索

if (preg_match('#^http#i', $url) === 1) {
    // Starts with http (case insensitive).
}

正则表达式允许执行更复杂的任务

if (preg_match('#^https?://#i', $url) === 1) {
    // Starts with http:// or https:// (case insensitive).
}

性能方面,你不需要创建一个新的字符串(不像substr),也不需要解析整个字符串,如果它不是以你想要的开始。第一次使用正则表达式(你需要创建/编译它)会有性能损失。

这个扩展维护一个编译规则的全局每线程缓存 表达式(最多4096)。 http://www.php.net/manual/en/intro.pcre.php

您可以使用下面的小函数检查字符串是以http还是https开头的。

function has_prefix($string, $prefix) {
   return substr($string, 0, strlen($prefix)) == $prefix;
}

$url   = 'http://www.google.com';
echo 'the url ' . (has_prefix($url, 'http://')  ? 'does' : 'does not') . ' start with http://';
echo 'the url ' . (has_prefix($url, 'https://') ? 'does' : 'does not') . ' start with https://';

使用大小写敏感():

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

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