我正在尝试检查一个字符串是否以http.我怎么做这个检查?
$string1 = 'google.com';
$string2 = 'http://www.google.com';
Run Code Online (Sandbox Code Playgroud)
Ken*_*ins 768
substr( $string_n, 0, 4 ) === "http"
Run Code Online (Sandbox Code Playgroud)
如果你想确保它不是另一个协议.我会使用http://,因为https也会匹配,以及http-protocol.com等其他东西.
substr( $string_n, 0, 7 ) === "http://"
Run Code Online (Sandbox Code Playgroud)
总的来说:
substr($string, 0, strlen($query)) === $query
Run Code Online (Sandbox Code Playgroud)
awg*_*wgy 597
用途strpos():
if (strpos($string2, 'http') === 0) {
// It starts with 'http'
}
Run Code Online (Sandbox Code Playgroud)
记住三个等号(===).如果你只使用两个,它将无法正常工作.这是因为如果在大海捞针中找不到针头strpos()会返回false.
Sid*_*Sid 83
还有strncmp()功能和strncasecmp()功能,非常适合这种情况:
if (strncmp($string_n, "http", 4) === 0)
Run Code Online (Sandbox Code Playgroud)
一般来说:
if (strncmp($string_n, $prefix, strlen($prefix)) === 0)
Run Code Online (Sandbox Code Playgroud)
该substr()方法的优点是strncmp()只需执行需要完成的操作,而无需创建临时字符串.
use*_*648 42
您可以使用一个简单的regex(更新版本从用户viriathus为eregi已废弃)
if (preg_match('#^http#', $url) === 1) {
// Starts with http (case sensitive).
}
Run Code Online (Sandbox Code Playgroud)
或者如果你想要一个不区分大小写的搜索
if (preg_match('#^http#i', $url) === 1) {
// Starts with http (case insensitive).
}
Run Code Online (Sandbox Code Playgroud)
正则表达式允许执行更复杂的任务
if (preg_match('#^https?://#i', $url) === 1) {
// Starts with http:// or https:// (case insensitive).
}
Run Code Online (Sandbox Code Playgroud)
性能方面,您不需要创建新的字符串(与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://';
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
568046 次 |
| 最近记录: |