我正在尝试检查字符串是否以http
开头。我该怎么办呢?
$string1 = 'google.com';
$string2 = 'http://www.google.com';
答案 0 :(得分:698)
使用substr函数返回字符串的一部分。
substr( $string_n, 0, 4 ) === "http"
如果你想确保它不是另一种协议。我会使用http://
代替,因为https也会匹配,以及http-protocol.com等其他内容。
substr( $string_n, 0, 7 ) === "http://"
总的来说:
substr($string, 0, strlen($query)) === $query
答案 1 :(得分:539)
使用strpos()
:
if (strpos($string2, 'http') === 0) {
// It starts with 'http'
}
记住三个等号(===
)。如果你只使用两个,它将无法正常工作。这是因为如果在大海捞针中找不到针,strpos()
将返回false
。
答案 2 :(得分:74)
还有strncmp()
函数和strncasecmp()
函数,非常适合这种情况:
if (strncmp($string_n, "http", 4) === 0)
一般来说:
if (strncmp($string_n, $prefix, strlen($prefix)) === 0)
substr()
方法的优势在于strncmp()
只需执行需要完成的操作,而无需创建临时字符串。
答案 3 :(得分:41)
您可以使用简单的正则表达式(用户 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
答案 4 :(得分:5)
您可以使用下面的小功能检查您的字符串是以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://';
答案 5 :(得分:-8)
还有工作:
if (eregi("^http:", $url)) {
echo "OK";
}